对于任何类型的T,keyof T 是T 的已知公共属性名称的联合。
例子:
interface Person {
age: number;
name: string;
}
type PersonKeys = keyof Person; // "age" | "name"
因此,您对keyof string 产生startsWith | endsWith | trim | ... 的假设是正确的。你可以在lookup type release notes了解更多。
扩展keyof
extends,在这种情况下,用于constrain the type of a generic parameter。示例:
<T, K extends keyof T>
K 因此只能是T 的公共属性名称。它与扩展类型或继承无关,与extending interfaces 相反。
extends keyof 的用法可能如下:
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const person: Person = {
age: 22,
name: "Tobias",
};
// name is a property of person
// --> no error
const name = getProperty(person, "name");
// gender is not a property of person
// --> error
const gender = getProperty(person, "gender");
除了documentation on index types,我找到了this helpful article。
在关键
in 用于定义一个index signature,我们想用字符串、数字或符号文字的联合来键入。结合keyof,我们可以使用它来创建一个所谓的映射类型,它重新映射原始类型的所有属性。
in keyof 的用法可能如下:
type Optional<T> = {
[K in keyof T]?: T[K]
};
const person: Optional<Person> = {
name: "Tobias"
// notice how I do not have to specify an age,
// since age's type is now mapped from 'number' to 'number?'
// and therefore becomes optional
};
除了documentation on mapped types,我又找到了this helpful article。
趣事:我们刚刚构建的Optional<T> 类型与官方Partial<T> 实用程序类型具有相同的签名!