[英]Typescript object indexer and key that doesn't match indexer type
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
的对象name: string
属性,并且它可以具有其他可能的键,所有键都必须是数字?
像这样:
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 but could end up as string at run-time
索引定义告诉我们number
但是我们可能在运行时以string
。
诚实的做法是使索引签名返回number | string
number | string
。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.