Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

typescript

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?

like image 558
Rick Avatar asked Jan 30 '17 23:01

Rick


People also ask

What does Keyof Typeof do?

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".

What does Keyof return?

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.

What is Keyof?

keyof is a keyword in TypeScript which is used to extract the key type from an object type.

Is Typeof TypeScript?

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.


1 Answers

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).

like image 156
Ryan Cavanaugh Avatar answered Sep 17 '22 12:09

Ryan Cavanaugh