keyof可操作对象/类/接口/基本类型
typeof只获取变量的类型,操作符的后面接的始终是一个变量,且需要运用到类型定义当中。
keyof的使用
操作接口
keyof 后面跟的是类型,操作符提取其属性的名称。
interface Boy {name: string;age: number;weight: number;}type boyName = keyof Boy; //通过keyof提取接口Boy的属性名称 name | age | weighttype boyNames = keyof Boy[]; // 提取的是数组的属性 length | push | remove | pop | concat ...const byn: boyName = 'name';const byns: boyNames = 'length';console.log(byn, byns);
操作类class
// 除了操作interface,keyof也可以操作classclass Person {name = 'John';age = 12;}const p: keyof Person = 'name';// const g: keyof Person = 'gender'; // 类型报错, 不能将类型“"gender"”分配给类型“keyof Person”console.log(p);
基本类型
// keyof除了支持interface和class外,也支持基本类型type str = keyof string;type num = keyof number;type sym = keyof symbol;// str --> "length" | "toString" | "concat" | "slice" | "indexOf" | "lastIndexOf" | "includes" | "charAt" | "charCodeAt" | "localeCompare" | "match" | ... 36 more ... | "replaceAll"const kof1: str = 'lastIndexOf';// num --> "toString" | "toLocaleString" | "valueOf" | "toFixed" | "toExponential" | "toPrecision"const kof2: num = 'toFixed';//sym --> "toString" | typeof Symbol.toPrimitive | typeof Symbol.toStringTag | "valueOf" | "description"const kof3: sym = 'toString';console.log(kof1, kof2, kof3);
keyof的实例运用
// 使用keyof和范型,多定义的类型进行范型保护function prop<T extends object, U extends keyof T>(obj: T, key: U): T[U] {return obj[key];}interface IpropObj {id: number;desc: string;}const propObj: IpropObj = {id: 100,desc: 'this is a prop',};const po: number = prop(propObj, 'id');console.group(po);
prop函数用于获取某个对象中指定属性的属性值,使用keyof操作符限定属性的类型。
使用了 TypeScript 的泛型和泛型约束。首先定义了 T 类型并使用 extends 关键字约束该类型必须是 object 类型的子类型,然后使用 keyof 操作符获取 T 类型的所有键,其返回类型是联合类型,最后利用 extends 关键字约束 K 类型必须为 keyof T 联合类型的子类型。
typeof的使用
typeof 操作符用于获取变量的类型,该操作符后面跟的必须是变量,且运用到类型type/interface等类型定义中。
type Man = {name: string;age: number;};const man: Man = {name: 'shen',age: 30,};// typeof 后边跟的是变量type typeM = typeof man;interface IM1 {man: typeof man;height: number;}const m1: typeM = {age: 12,name: 'shen',};const m2: IM1 = {man: {age: 12,name: 'shen',},height: 170,};console.log(m1, m2);
keyof和typeof结合使用
const COLORS = {red: 'red',blue: 'blue',};// 首先通过typeof操作符获取color变量的类型,然后通过keyof操作符获取该类型的所有键,// 即字符串字面量联合类型 'red' | 'blue'type colors = keyof typeof COLORS;let c: colors = 'red';c = 'blue';// c = 'black'; 类型报错,c: "red" | "blue" 为两个类型console.log(c);
