简体   繁体   中英

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.

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).

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'];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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