Typescript Record<number, string> 接受 Key 上的数字
Typescript Record<number, string> accepts number on Key
我是 typescript 的新手,还有很多东西要学习,但我偶然发现了这个 code,这让我对 Record 实用程序类型感到非常困惑。
此代码适用于 playground
const data = async (name: string, id: number): Promise<Record<number,string>> => {
const obj = {
foo: 'bar', //shouldn't this not work since I've used 'number'?
}
return obj
}
这个没有(第2行)
const foo1: Record<string, string> = { foo: 'bar' }
const foo2: Record<number, string> = { foo: 'bar' }
这是为什么?我也不确定 'key' 中应该使用哪种数据类型。尝试打字稿游乐场
这是因为TS要兼容JavaScript.
考虑这个纯 js 代码:
const foo={
0:42
}
const x = foo['0'] // number
const y = foo[0] // number
您可能已经注意到,JS 允许您同时使用字符串和数字键 0: 42
同时查看 js 和 ts 文档:
Property names
Property names are string or Symbol. Any other value, including a number, is coerced to a string. This outputs 'value', since 1 is coerced into '1'.
It is possible to support both types of indexers, but the type returned from a numeric indexer must be a subtype of the type returned from the string indexer. This is because when indexing with a number
, JavaScript will actually convert that to a string
before indexing into an object. That means that indexing with 100
(a number
) is the same thing as indexing with "100"
(a string
), so the two need to be consistent.
这是为什么呢?我也不确定 'key'.
中应该使用哪种数据类型
TypeScript 已为键内置类型:type PropertyKey = string | number | symbol
您可以在不声明的情况下使用 PropertyKey
。此类型内置
我是 typescript 的新手,还有很多东西要学习,但我偶然发现了这个 code,这让我对 Record 实用程序类型感到非常困惑。
此代码适用于 playground
const data = async (name: string, id: number): Promise<Record<number,string>> => {
const obj = {
foo: 'bar', //shouldn't this not work since I've used 'number'?
}
return obj
}
这个没有(第2行)
const foo1: Record<string, string> = { foo: 'bar' }
const foo2: Record<number, string> = { foo: 'bar' }
这是为什么?我也不确定 'key' 中应该使用哪种数据类型。尝试打字稿游乐场
这是因为TS要兼容JavaScript.
考虑这个纯 js 代码:
const foo={
0:42
}
const x = foo['0'] // number
const y = foo[0] // number
您可能已经注意到,JS 允许您同时使用字符串和数字键 0: 42
同时查看 js 和 ts 文档:
Property names Property names are string or Symbol. Any other value, including a number, is coerced to a string. This outputs 'value', since 1 is coerced into '1'.
It is possible to support both types of indexers, but the type returned from a numeric indexer must be a subtype of the type returned from the string indexer. This is because when indexing with a
number
, JavaScript will actually convert that to astring
before indexing into an object. That means that indexing with100
(anumber
) is the same thing as indexing with"100"
(astring
), so the two need to be consistent.
这是为什么呢?我也不确定 'key'.
中应该使用哪种数据类型TypeScript 已为键内置类型:type PropertyKey = string | number | symbol
您可以在不声明的情况下使用 PropertyKey
。此类型内置