The first type: used with the interface, returning the union type
interface Person {
name: string;
age: number;
location: string;
}
type K1=keyof Person; // "name" | "age" | "gender"
let a:K1='name'
The second type: used together with typeof, can return the joint type of the object key, and can also be used with
const TIME_TYPE = {
FIXED_TIME_RANGE: 'FIXED_TIME_RANGE',
DYNAMIC_TIME_RANGE: 'DYNAMIC_TIME_RANGE',
};
let a:keyof typeof TIME_TYPE //'FIXED_TIME_RANGE'|'DYNAMIC_TIME_RANGE'
The third way: use with classes
class Person {
name: string = "Semlinker";
getInfo(){
console.log(this.name)
}
}
let sname: keyof Person=‘getInfo’
If getInfo is written as getInfo1, the following error will be reported
The fourth type: keyof also supports basic data types, as follows
Fifth: use type parameters in generic constraints
You can declare a type parameter that is constrained by another type parameter. For example, now we want to get this property from an object using the property name. And we want to make sure that this property exists on the object obj
, so we need to use constraints between these two types.
function getProperty<T, K extends keyof T>(obj: T, key: K) {
return obj[key];
}
let x = { a: 1, b: 2, c: 3, d: 4 };
getProperty(x, "a"); // okay
getProperty(x, "m"); //类型“"m"”的参数不能赋给类型“"a" | "b" | "c" | "d"”的参数。