Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/ms-access/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Typescript对象索引器和不带';t匹配索引器类型_Javascript_Typescript - Fatal编程技术网

Javascript Typescript对象索引器和不带';t匹配索引器类型

Javascript Typescript对象索引器和不带';t匹配索引器类型,javascript,typescript,Javascript,Typescript,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 } 对于上述示例,建议的解决方法是什么,例如,我知道一个对象具有名称:st

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
}
对于上述示例,建议的解决方法是什么,例如,我知道一个对象具有
名称: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

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

这是不可能的,因为索引器中的
索引
也可能是
名称