What does "keyof typeof" mean in TypeScript? - Stack Overflow
keyof
takes an object type and returns a type that accepts any of the object's keys.
type Point = { x: number; y: number };
type P = keyof Point; // type '"x" || "y"'
const coordinate: P = 'z' // Type '"z"' is not assignable to type '"x" | "y"'.
typeof with TypeScript types
typeof
behaves differently when called on javascript objects, to when it is called on typescript types.
- TypeScript uses javascript's typeof when called on javascript values at runtime and returns one of
"undefined", "object", "boolean", "number", "bigint", "string", "symbol", "function"
- TypeScript's typeof is called on type values, but can also be called on javascript values when in a type expression. It can also infer the type of javascript objects, returning a more detailed object type.
type Language = 'EN' | 'ES';
const userLanguage: Language = 'EN';
const preferences = { language: userLanguage, theme: 'light' };
console.log(typeof preferences); // "object"
type Preferences = typeof preferences; // type '{language: 'EN''; theme: string; }'
Because the second typeof preferences
is in a type expression it is actually TypeScript's own typeof
that get called, and not javascript's.
keyof typeof
Because keyof
is a TypeScript concept we will be calling TypeScript's verion of typeof
.
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".
type PreferenceKeys = keyof typeof preferences; // type '"language" | "theme"'
Không có nhận xét nào:
Đăng nhận xét