Is it possible to use `keyof` operator on literals instead of interfaces?

前端 未结 2 1259
春和景丽
春和景丽 2021-02-01 12:00

I have an object literal such as the following (all properties are known at compile time):

const foo = {
  \"hello\": \"hola\"
};

If foo<

2条回答
  •  失恋的感觉
    2021-02-01 13:00

    keyof operates on types, but foo is a value. But the typeof operator takes a value and produces its type, so you can use keyof typeof foo to do this.

    Note that this only works if you haven't associated an interface with the object literal (thanks radicand).

提交回复
热议问题