I have an object literal such as the following (all properties are known at compile time):
const foo = { "hello": "hola" };
If foo
were an interface rather than a variable, I could easily do something like
/** THEORETICAL ONLY - Does not compile! */ function translate(input: keyof foo): string { return foo[input]; }
However, doing so with a variable does not work, since the compiler cannot find an interface with the name foo
.
Does Typescript support keyof
operations on object literals whose values are known at compile time?
keyof typeof will infer the type of a javascript object and return a type that is the union of its keys. Because it can infer the exact value of the keys it can return a union of their literal types instead of just returning "string".
keyof T returns a union of string literal types. The extends keyword is used to apply constraints to K, so that K is one of the string literal types only. extends means “is assignable” instead of “inherits”' K extends keyof T means that any value of type K can be assigned to the string literal union types.
keyof is a keyword in TypeScript which is used to extract the key type from an object type.
TypeScript comes with some built-in type guards: typeof and instanceof . They're very useful, but have limited scope. For example, typeof can only be used to check string , number , bigint , function , boolean , symbol , object , and undefined types.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With