What does “keyof typeof” mean in TypeScript?

后端 未结 4 1154
渐次进展
渐次进展 2020-12-24 00:11

Example:

Explain to me what keyof typeof means in TypeScript

enum ColorsEnum {
    white = \'#ffffff\',
    black = \'#000000\',
}

type         


        
4条回答
  •  礼貌的吻别
    2020-12-24 00:52

    For finding the type of any values we use typeof operation. For eg

    const user = {
       getPersonalInfo(){},
       getLocation(){}
    }
    

    Here user is a value so here typeof operator comes in handy

    type userType = typeof user
    

    Here userType gives type information that user is an object which have two properties getPersonalInfo and getLocation and both are functions return void

    Now if you want to find the keys of user you can use keyof

    type userKeys = keyof userType
    

    which says userKeys= 'getPersonalInfo'| 'getLocation'

    Beware if you try to get user's key like type userKeys = keyof user you will get an error 'user' refers to a value, but is being used as a type here. Did you mean 'typeof user'?

提交回复
热议问题