名称'keyof'是TypeScript中的一个关键字,用于获取一个类型的所有属性名称组成的联合类型。
具体来说,'keyof'关键字可以用于以下场景:
type Person = {
name: string;
age: number;
gender: string;
};
type PersonKeys = keyof Person; // "name" | "age" | "gender"
type Person = {
name: string;
age: number;
gender: string;
};
const person: Person = {
name: "John",
age: 25,
gender: "male",
};
function getProperty(obj: Person, key: keyof Person) {
return obj[key];
}
const nameValue = getProperty(person, "name"); // "John"
type Person = {
name: string;
age: number;
gender: string;
};
function getProperty<T, K extends keyof T>(obj: T, key: K) {
return obj[key];
}
const person: Person = {
name: "John",
age: 25,
gender: "male",
};
const nameValue = getProperty(person, "name"); // "John"
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云