【问题标题】:Typescript Record<number, string> accepts number on KeyTypescript Record<number, string> 接受 Key 上的数字
【发布时间】:2021-11-07 11:47:35
【问题描述】:

我是 typescript 的新手,还有很多东西要学习,但我偶然发现了这个 code,这让我对 Record 实用程序类型感到非常困惑。

此代码适用于操场

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 promise


【解决方案1】:

这是因为 TS 应该兼容 JavaScript。

考虑一下这个纯 js 代码:

const foo={
  0:42
}

const x = foo['0'] // number
const y = foo[0] // number

您可能已经注意到,JS 允许您对0: 42 使用字符串和数字键

查看 js 和 ts 文档:

js explanation

属性名称 属性名称是字符串或符号。任何其他值(包括数字)都被强制转换为字符串。这会输出 'value',因为 1 被强制转换为 '1'。

ts explanation

可以同时支持这两种类型的索引器,但是从数字索引器返回的类型必须是从字符串索引器返回的类型的子类型。这是因为当使用 number 进行索引时,JavaScript 实际上会在索引到对象之前将其转换为 string。这意味着使用100number)进行索引与使用"100"string)进行索引是一回事,因此两者需要保持一致。

这是为什么呢?我也不确定在“键”中应该使用哪种数据类型。

TypeScript 已为键内置类型:type PropertyKey = string | number | symbol

您可以在不声明的情况下使用PropertyKey。这种类型是内置的

【讨论】:

    猜你喜欢
    • 2019-09-07
    • 2021-04-20
    • 1970-01-01
    • 2020-08-20
    • 2022-09-23
    • 2020-06-19
    • 2017-12-25
    • 2021-12-31
    • 2022-12-02
    相关资源
    最近更新 更多