4 min read
•Question 16 of 48mediumWhat are keyof and typeof in TypeScript?
Type operators for extracting types.
What You'll Learn
- keyof operator
- typeof operator
- Combining them
keyof Operator
Gets union of all keys of a type.
code.tsTypeScript
interface User {
id: number;
name: string;
email: string;
}
type UserKeys = keyof User;
// "id" | "name" | "email"
function getValue(user: User, key: keyof User) {
return user[key];
}typeof Operator
Gets the type of a value.
code.tsTypeScript
const config = {
host: "localhost",
port: 3000,
ssl: true
};
type Config = typeof config;
// { host: string; port: number; ssl: boolean; }
function updateConfig(updates: Partial<typeof config>) {
// ...
}Combining keyof and typeof
code.tsTypeScript
const colors = {
red: "#ff0000",
green: "#00ff00",
blue: "#0000ff"
};
type ColorName = keyof typeof colors;
// "red" | "green" | "blue"
function getColor(name: ColorName): string {
return colors[name];
}