Typescript literal types used as key to indexer

前端 未结 1 1790
野的像风
野的像风 2021-01-14 09:12

Is there any way to define a typescript literal type which can be used as a string key in an indexer?

type TColorKey = \'dark\' | \'light\';

interface Color         


        
相关标签:
1条回答
  • 2021-01-14 09:45

    Yes, it is possible thanks to a new feature called Mapped types. Just make sure you're using nightly version of typescript compiler (typescript@next) because it's not in stable build yet (at the time I'm writing this).

    type TColorKey = "dark" | "light";
    
    type TColorMap = { [P in TColorKey]: Color };
    
    0 讨论(0)
提交回复
热议问题