是什么
可遍历类型的所有属性,keyof 将提取属性的的字面量类型,然后构成一个联合类型。 keyof 是引索类型查询操作符。keyof T;
keyoof 返回联合类型
interface Person {
name: string;
age: number;
isChina: boolean;
}
interface Map<T> {
[K: string]: T;
}
class PersonClass {
name = 'stone';
getName(){
return this.name;
}
}
let person: keyof Person;
// let person: "name" | "age" | "isChina"
let person1: keyof Person[];
// let person1: number | "length" | "toString" | "toLocaleString" | "pop" | "push" | "concat" | "join" | "reverse" | "shift" | "slice" | "sort" | "splice" | "unshift" | "indexOf" | "lastIndexOf" | ... 6 more ... | "reduceRight"
let person2: keyof Map<string>;
// let person2: string | number
let person3: keyof PersonClass;
// let person3: "name" | "getName"
person3 = 'name';
person3 = 'getName';
// person3 = 'age'; // 不能将类型“"age"”分配给类型“"name" | "getName"”。ts(2322)
let k1: keyof string;
// let k1: number | "length" | "toString" | "concat" | "slice" | "indexOf" | "lastIndexOf" | "charAt" | "charCodeAt" | "localeCompare" | "match" | "replace" | "search" | "split" | "substring" | ... 6 more ... | "valueOf"
let k2: keyof number;
// let k2: "toString" | "toLocaleString" | "valueOf" | "toFixed" | "toExponential" | "toPrecision"
let k3: keyof boolean;
// let k3: "valueOf"
let k4: keyof null;
// let k4: never
let k5: keyof undefined;
// let k5: never
keyof 保证属性的安全访问
type Todo = {
name: string;
age: number;
isChina: boolean;
};
let todo: Todo = {
name: 'stone',
age: 18,
isChina: true
};
function prop<T extends object, K extends keyof T>(obj: T, key: K) {
return obj[key];
}
let l_name = prop(todo, 'name');
// let l_name: string
let l_age = prop(todo, 'age');
// let l_age: number
let l_ischina = prop(todo, 'isChina');
// let l_ischina: boolean
// let l_address = prop(todo, 'address');
// 类型“"address"”的参数不能赋给类型“"name" | "age" | "isChina"”的参数。ts(2345)
enum Currency {
CNY = 6,
EUR = 8,
USD = 10,
};
const CurrencyName = {
[Currency.CNY]: '人民币',
[Currency.EUR]: '英镑',
[Currency.USD]: '美元',
};
function getCurrencyName<T, K extends keyof T>(map: T, key: K): T[K] {
return map[key];
}
let name_1 = getCurrencyName(CurrencyName, Currency.CNY);
let name_2 = getCurrencyName(CurrencyName, Currency.EUR);
let name_3 = getCurrencyName(CurrencyName, Currency.USD);