gpt4 book ai didi

typescript - 什么是记录类型?

转载 作者:搜寻专家 更新时间:2023-10-30 20:28:42 25 4
gpt4 key购买 nike

什么是Record<K, T>在 typescript 中是什么意思?

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>

参见 Typescript 2.1

还有 Advanced Types页面提及 RecordReadonly 旁边的映射类型标题下, Partial , 和 Pick ,在它的定义中:

type Record<K extends string, T> = {
[P in K]: T;
}

Readonly, Partial and Pick are homomorphic whereas Record is not. One clue that Record is not homomorphic is that it doesn’t take an input type to copy properties from:

type ThreeStringProps = Record<'prop1' | 'prop2' | 'prop3', string>

就是这样。除了上面的引述,没有其他提及 Recordtypescriptlang.org .

问题

  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}

最佳答案

  1. Can someone give a simple definition of what Record is?

A Record<K, T>是一个对象类型,其属性键是 K其属性值为 T .即 keyof Record<K, T>相当于K , 和 Record<K, T>[K]是(基本上)等同于T .

  1. Is Record<K,T> merely a way of saying "all properties on this object will have type T"? Probably not all objects, since K has some purpose...

如您所见,K有一个目的......将属性键限制为特定值。如果你想接受所有可能的字符串值键,你可以做类似 Record<string, T> 的事情。 , 但惯用的方法是使用 index signature喜欢{ [k: string]: T } .

  1. Does the K generic forbid additional keys on the object that are not K, or does it allow them and just indicate that their properties are not transformed to T?

它并不完全“禁止”附加键:毕竟,通常允许一个值具有其类型中未明确提及的属性……但它不会识别此类属性的存在:

declare const x: Record<"a", string>;
x.b; // error, Property 'b' does not exist on type 'Record<"a", string>'

它会将它们视为 excess properties有时会被拒绝:

declare function acceptR(x: Record<"a", string>): void;
acceptR({a: "hey", b: "you"}); // error, Object literal may only specify known properties

有时接受:

const y = {a: "hey", b: "you"};
acceptR(y); // okay
  1. With the given example:

     type ThreeStringProps = Record<'prop1' | 'prop2' | 'prop3', string>

    Is it exactly the same as this?:

     type ThreeStringProps = {prop1: string, prop2: string, prop3: string}

是的!

关于typescript - 什么是记录类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51936369/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com