在 TypeScript 中,一些类型是使用 extends keyof
定义的或 in keyof
.我试图理解它们的意思,但到目前为止我没有成功。
我得到的是 keyof
alone 返回一个联合类型,它具有所有名称作为可能值,这些值作为属性名称存在于您在 keyof
之后指定的类型上.
type T = keyof string;
T
因此相当于 startsWith | endsWith | trim | substring | ...
.
这是正确的吗?
现在,如果我试着想一想 extends keyof
和 in keyof
意思是,我的直觉是这样的:
-
extends keyof
是从T
派生的任何类型,即它具有所有这些可能的值,但可能更多。 -
in keyof
是从T
获取值的任何类型,但不一定全部(有可能,但可能更少)。
所以,从这个 POV extends keyof
会描述一个 >=
关系,in keyof
会描述一个 <=
关系。这样对吗?如果不是,那什么是正确的?
最佳答案
对于任何类型 T
, keyof T
是T
的已知公共(public)属性名称的联合.
例子:
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
的公共(public)属性名称.它与扩展类型或继承无关,与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 .
Fun fact: The
Optional<T>
type we've just built has the same signature as the officialPartial<T>
utility type!
关于typescript - 在 TypeScript 中, "extends keyof"和 "in keyof"是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57337598/