英文:
Difference between Record<A, B> and {[key: A]: B}
问题
类型A和类型B之间的区别是什么?
type A = {[key: string]: string | number | boolean | null}
type B = Record<string, string | number | boolean | null>
英文:
What is the difference between the types A and B?
type A = {[key: string]: string | number | boolean | null}
type B = Record<string, string | number | boolean | null>
答案1
得分: 2
使用Record
时,可以使用字符串的并集作为索引,如下所示:
// 可以
type B = Record<'a' | 'b', string | number | boolean | null>;
但是在interface
索引中,不能使用联合类型,如下所示:
// 错误
type A = { [key: 'a' | 'b']: string | number | boolean | null };
如果要了解为什么A_1
起作用,请参阅Symbol and Template String Pattern Index Signatures。
英文:
There is a difference in indexing. When you use Record
, you can use a union of string:
// ok
type B = Record<'a' | 'b', string | number | boolean | null>;
// error
type A = { [key: 'a' | 'b']: string | number | boolean | null };
// works :D
type A_1 = { [key: `a${string}` | `$b${string}`]: string | number | boolean | null };
But you are not able to use unions in aka interface
indexing (see type A).
Please see Symbol and Template String Pattern Index Signatures to better understanding why A_1
works
答案2
得分: 1
在一般情况下,类型 A 和类型 B 在功能上是等价的,它们表示具有任意字符串键和值的对象类型,这些值可以是字符串、数字、布尔值或空值。
区别在于用于定义它们的语法,类型 A 使用索引签名语法,而类型 B 使用 Record 实用程序类型。
英文:
In general, type A and type B are functionally equivalent and represent object types with arbitrary string keys and values that can be string, number, boolean, or null.
The difference lies in the syntax used to define them, with type A using index signature syntax and type B using the Record utility type.
答案3
得分: 1
没有功能上的区别。虽然一般来说,“Record”类型对人类来说可能更容易阅读。
“Record”实用类型已内置于TypeScript中,但不需要任何特殊的语法或定义。它只是一种简写,你可以在TypeScript的“lib.es5.d.ts”文件中找到它的源定义:
/**
* 构造一个具有类型T的属性集K的类型
*/
type Record<K extends keyof any, T> = {
[P in K]: T;
};
如果在支持TypeScript的IDE中,包括TypeScript Playground,将鼠标悬停在类型B
上,你会看到它被转换为:
// type B = Record<string, string | number | boolean | null>
type B = {
[x: string]: string | number | boolean | null;
}
这与你的类型定义A
完全相同。
英文:
There is no functional difference. Though generally the Record
type can be quite a bit easier for humans to read.
The Record
utility type is built into TypeScript, but it doesn't require any special syntax or anything to define it. It's simply a shorthand, and you can find its source definition within TypeScript's lib.es5.d.ts
file:
/**
* Construct a type with a set of properties K of type T
*/
type Record<K extends keyof any, T> = {
[P in K]: T;
};
If you were to hover over your type B
in an IDE with TypeScript support, including the TypeScript Playground, you will see that it gets transformed to this:
// type B = Record<string, string | number | boolean | null>
type B = {
[x: string]: string | number | boolean | null;
}
Which is identical to your type definition of A
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论