Reputation: 23
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.
Upvotes: 0
Views: 714
Reputation: 250882
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'];
Upvotes: 2