我是typescript的新手,还有很多要学习,但我绊倒了这段代码,这对我来说是相当混乱的记录实用程序类型。
这个代码在操场上运行
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
}
这个没有(第二行)
const foo1: Record<string, string> = { foo: 'bar' }
const foo2: Record<number, string> = { foo: 'bar' }
为什么会这样?我也不确定应该在"键"中使用什么样的数据类型。尝试typescript playground
这是因为TS应该与JavaScript兼容。
考虑以下纯js代码:
const foo={
0:42
}
const x = foo['0'] // number
const y = foo[0] // number
你可能已经注意到,JS允许你使用字符串和数字键的0: 42
查看js和ts文档:
js解释
属性名属性名是字符串或符号。任何其他值,包括数字,都被强制转换为字符串。这将输出'value',因为1被强制转换为'1'。
ts解释
可以同时支持这两种类型的索引器,但是从数字索引器返回的类型必须是字符串索引器返回类型的子类型。这是因为当索引
number
时,JavaScript实际上会在索引对象之前将其转换为string
。这意味着索引100
(anumber
)与索引"100"
(astring
)是一样的,所以两者需要保持一致。
这是为什么?我也不确定应该在"键"中使用哪种数据类型。
TypeScript内置了type for key:type PropertyKey = string | number | symbol
您可以使用PropertyKey
不声明。这种类型内置于