TypeScript 7 reference · Type Operators and Keywords
TypeScript keyof Operator
Produce a union of an object type's property names: keyof { a: 1; b: 2 } is 'a' | 'b'.
TypeScript 7 Since 2.1
Syntax
keyof Type
Examples
interface User {
id: number;
name: string;
}
type UserKey = keyof User; // "id" | "name"
const k: UserKey = "name";
console.log(k);
Output
name
function getField<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const user = { id: 1, name: "Ana" };
console.log(getField(user, "name"));
// @ts-expect-error: "email" is not a key of user
getField(user, "email");
Output
Ana
Version history
| Version | Change |
|---|---|
| TypeScript 2.1 | Added |
Related
Type[Key]· Look up the type of a property with Type['key'], or of array elements with Type[number].mapped types ({ [K in Keys]: … })· Create a new object type by transforming every property of another, the way Partial and Readonly are built.typeof (type query)· In a type position, typeof takes the type of a value or function, so you don't have to write it twice.- TypeScript keyof, typeof and Indexed Access · tutorial