配列から型を取得 #
typeof xxx[number]
const names = ["Alice", "Bob", "Charlie", "David"] as const;
type Names = (typeof names)[number]; // "Alice" | "Bob" | "Charlie" | "David"
オブジェクトのキーから型を取得 #
keyof typeof xxx
const favoriteColors = {
alice: "cyan",
bob: "magenta",
charlie: "yellow",
david: "black",
} as const;
type FavoriteColors = keyof typeof favoriteColors; // "alice" | "bob" | "charlie" | "david"
オブジェクトのバリューから型を取得 #
typeof xxx[keyof typeof xxx]
const favoriteColors = {
alice: "cyan",
bob: "magenta",
charlie: "yellow",
david: "black",
} as const;
type FavoriteColors = (typeof favoriteColors)[keyof typeof favoriteColors]; // "cyan" | "magenta" | "yellow" | "black"