ts(keyof,typeof)
ts(keyof,typeof)
- keyof 获取某类型的键,返回联合类型
interface Person {
hair: string;
eyesColor: string;
}
let P1 = keyof;
Penson; //"hair"||'eyesColor'
//特别
type K3 = keyof { [x: string]: Person }; // string | number
- typeof 获取某值变量的类型
let xiaoming = {
hair: "black",
};
type K = typeof xiaoming; //K={hair:string}
const COLORS = {
red: "red",
blue: "blue",
};
// 首先通过typeof操作符获取color变量的类型{red:string,blue:string},然后通过keyof操作符获取该类型的所有键,
// 即字符串字面量联合类型 'red' | 'blue'
type Colors = keyof typeof COLORS;
let color: Colors;
color = "red"; // Ok
color = "blue"; // Ok
// Type '"yellow"' is not assignable to type '"red" | "blue"'.
color = "yellow"; // Error
参考
本文来自作者:小黄H的笔记,转载请经过本人同意