gpt4 book ai didi

javascript - Typescript 对象索引器和与索引器类型不匹配的键

转载 作者:搜寻专家 更新时间:2023-10-30 21:26:23 26 4
gpt4 key购买 nike

Typescript 文档显示了以下示例:

interface NumberDictionary {
[index: string]: number;
length: number; // ok, length is a number
name: string; // error, the type of 'name' is not a subtype of the indexer
}

以上示例的推荐解决方法是什么,例如我有一个对象,我知道它有一个 name: string 属性,它可以有任何其他可能的键,所有键都必须是数字?

最佳答案

问题是这样的类型本质上是不一致的。考虑以下代码:

let prop = Math.random() > 0.5 ? "name" : "other"
let dic: NumberDictionary;
let value = dic[prop] // typed as number but could end up as string at run-time

索引定义告诉我们 number 但我们可能会在运行时以 string 结束。

诚实的做法是让索引签名返回number |字符串

interface NumberDictionary {
[index: string]: number | string;
length: number;
name: string;
}
let prop = Math.random() > 0.5 ? "name" : "other"
let dic: NumberDictionary;
let value = dic[prop] // typed as number | string we need a type guard to tell teh difference

诚实的解决方案可能并不总是实用的,并且在充分意识到危险的情况下,您可以定义一个交集类型,让您摆脱不一致:

type NumberDictionary = {
[index: string]: number;
} & {
length: number;
name: string;
}

let prop = Math.random() > 0.5 ? "neverName" : "other"
let dic: NumberDictionary = {
name: "",
length: 1
} as NumberDictionary; // type assertion necessary, ts will still complain here about the inconsistentcy
let value = dic[prop] // typed as number, hope everyone avoids passing in name

关于javascript - Typescript 对象索引器和与索引器类型不匹配的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54619978/

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