问题描述
在 TypeScript 中,某些类型是使用 extends keyof
或 in keyof
定义的.我试图理解它们的意思,但到目前为止我没有成功.
In TypeScript, some types are defined using extends keyof
or in keyof
. I have tried to understand what they mean, but so far I didn't succeed.
我得到的是 keyof
单独返回一个联合类型,该类型将所有名称作为可能的值存在于您在 keyof
之后指定的类型上的属性名称中.
What I got is that keyof
alone returns a union type which has all the names as possible values that are existent as property names on the type that you specify after keyof
.
type T = keyof string;
T
因此等价于 startsWith |结束于 |修剪 |子串 |...
.
这是正确的吗?
现在,如果我尝试思考 extends keyof
和 in keyof
是什么意思,我的直觉是这样的:
Now, if I try to think about what extends keyof
and in keyof
mean, my gut feeling says the following:
extends keyof
是从T
派生的任何类型,即它具有所有这些可能的值,但可能更多.in keyof
是从T
中获取值的任何类型,但不一定是全部(可能,但可能更少).
extends keyof
is any type that derives fromT
, i.e. it has all these possible values, but maybe more.in keyof
is any type that takes values fromT
, but not necessarily all of them (it's possible, but maybe less).
因此,从这个 POV extends keyof
将描述一个 >=
关系,in keyof
将描述一个 <=
关系.这样对吗?如果不是,什么是正确的?
So, from this POV extends keyof
would describe a >=
relation, in keyof
would describe a <=
relation. Is this correct? If not, what would be correct?
推荐答案
对于任何类型 T
,keyof T
是 的已知公共属性名称的并集>T
.
For any type T
, keyof T
is the union of known, public property names of T
.
示例:
interface Person {
age: number;
name: string;
}
type PersonKeys = keyof Person; // "age" | "name"
您假设 keyof string
产生 startsWith |结束于 |修剪 |...
因此是正确的.您可以在 查找类型发行说明.
Your assumption that keyof string
yields startsWith | endsWith | trim | ...
is therefore correct. You can learn more about it in the lookup type release notes.
extends
用于 限制泛型参数的类型.示例:
K
因此只能是T
的公共属性名称.它与扩展类型或继承无关,与 扩展相反接口.
K
can therefor only be a public property name of T
. It has nothing to do with extending a type or inheritance, contrary to 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");
in
用于定义 索引签名,我们想用字符串、数字或符号文字的联合输入.结合keyof
,我们可以使用它来创建所谓的映射类型,它重新映射原始类型的所有属性.
in
is used when we're defining an index signature that we want to type with a union of string, number or symbol literals. In combination with keyof
we can use it to create a so called mapped type, which re-maps all properties of the original type.
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
};
除了关于映射类型的文档,我再次找到了这篇有用的文章一>.
有趣的事实:我们刚刚构建的 Optional
类型具有与官方 部分
实用程序类型!
这篇关于在 TypeScript 中,“extends keyof"是做什么的?和“in keyof"意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!