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

参考

原文链接

posted @ 2023-02-17 15:31  小黄H  阅读(81)  评论(0编辑  收藏  举报