简体   繁体   English

打字稿索引联合类型

[英]Typescript index union type

I'm working with typescript and I have an object with with fields referred to by both strings and numbers. 我正在使用打字稿,并且我有一个对象,它的字段由字符串和数字共同引用。 I know if it is indexed by just strings I can specify the type with 我知道它是否仅由字符串索引我可以使用指定类型

var object: {[index: string]: number}

Is there a way to do this that will allow the index to be either a string or a number? 有没有一种方法可以使索引为字符串或数字? I've tried var object: {[index: string|number]: number} with no luck. 我尝试了var object: {[index: string|number]: number} ,但没有运气。

The following works in the TypeScript playground... essentially, this is the behaviour you are after anyway (so you don't need to use a union type). 以下内容在TypeScript游乐场中起作用...本质上,这就是您要执行的行为(因此,您无需使用联合类型)。

var object: {[index: string]: number};

// Allowed
object[0] = 1;
object['idx'] = 2;

// Not allowed
object[1] = 'string';
object['other'] = 'string';

// Types inferred as number
var a = object[0];
var b = object['idx'];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM