What does “keyof typeof” mean in TypeScript?

后端 未结 4 1178
渐次进展
渐次进展 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:53

    Common misconception about TypeScript

    TypeScript is often described as a type layer on top of JavaScript runtime. As if types and values lived on separate planes. However, in TypeScript, some things are types and values at the same time.

    This is true for:

    • classes,
    • enums,
    • namespaces.

    When can you use keyof?

    The keyof keyword only works on the type level. You cannot apply it to a JavaScript value.

    When do you need keyof typeof?

    When you're dealing with something that is a type and a value at the same time (like a class or an enum), but you're interested specifically in what the type of that value is.

    The simplest example:

    const foo = { bar: 42 }; // foo is a value
    type Foo = typeof foo; // Foo is the type of foo
    
    type KeyOfFoo = keyof Foo; // "keyof Foo" is the same as "keyof typeof foo", which is "bar"
    

    In general, when you see this:

    type A = keyof typeof B;
    

    the typeof B part tells TypeScript to look at the type of B. You can think of it as casting B to its type. Sort of like casting a two-dimensional object to a one-dimensional space.

    Since typeof B is a type, not a value, we can now use keyof on it.

    Example

    Classes are types and values. You can call them, but you can also use keyof on them.

    declare class Foo {
        static staticProperty: string;
    
        dynamicProperty: string;
    }
    
    type Constructor = typeof Foo;
    type Instance = Foo;
    
    type A = keyof Constructor; // "prototype" | "staticProperty"
    type B = keyof Instance; // "dynamicProperty"
    

    By using typeof together with keyof, we can toggle between using keyof against the instance type and the constructor type.

提交回复
热议问题