Record<K, T>
在打字稿中是什么意思?
Typescript 2.1 引入了 Record
类型,举例说明:
> // For every properties K of type T, transform it to U > function mapObject<K extends string, T, U>(obj: Record<K, T>, f: (x: T) => U): Record<K, U> > > ``` 见 [打字稿2.1](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-1.html#partial-readonly-record-and-pick) And the [Advanced Types](https://www.typescriptlang.org/docs/handbook/advanced-types.html) page mentions `Record` under the Mapped Types heading alongside `Readonly` , `Partial` , and `Pick` , in what appears to be its定义: > ``` > type Record<K extends string, T> = { > [P in K]: T; > } > > ``` > Readonly、Partial 和 Pick 是同态的,而 Record 不是。 Record 不是同态的一个线索是它不需要输入类型来复制属性: > > ``` > type ThreeStringProps = Record<'prop1' | 'prop2' | 'prop3', string> > > ``` 就是这样。除了上述引用之外,typescriptlang.org 上没有其他提及 `Record` [。](https://www.google.com/search?q=site:https://www.typescriptlang.org/+record&filter=0&biw=1372&bih=835) ## 问题 1. 有人可以简单定义 `Record` 是什么吗? 2. `Record<K,T>` 仅仅是一种说法“这个对象上的所有属性都将具有类型 `T` ”吗?可能不是 _所有_ 属性,因为 `K` 有一些用途...... 3. `K` 泛型是否禁止对象上不是 `K` 的附加键,还是允许它们并仅指示它们的属性未转换为 `T` ? 4. 使用给定的示例:
type ThreeStringProps = Record<'prop1' | 'prop2' | 'prop3', string>
和这个完全一样吗?:
type ThreeStringProps = {prop1: string, prop2: string, prop3: string}
”`
原文由 Matthias 发布,翻译遵循 CC BY-SA 4.0 许可协议
A
Record<K, T>
是一种对象类型,其属性键为K
,其属性值为T
。也就是说,keyof Record<K, T>
等价于K
,而Record<K, T>[K]
(基本上)等价于T
正如您所注意到的,
K
有一个目的……将属性键限制为特定值。如果您想接受所有可能的字符串值键,您可以执行类似Record<string, T>
的操作,但惯用的做法是使用 索引签名,如{ [k: string]: T }
。它并没有完全“禁止”附加键:毕竟,通常允许一个值具有未在其类型中明确提及的属性……但它不会识别出这样的属性存在:
它会将它们视为有时会被拒绝的 多余属性:
有时接受:
是的!
希望有帮助。祝你好运!