Reputation: 28483
Not a big deal but I was wondering if it's possible to access an object using a non-string key AND define that it will return the same type whatever is accessed. I can figure out how to do both separately or can "laboriously" do both together.
I guess I want something like:
var DEFINITIONS: {[key: 'non-string']: Definition} = { ... }
or
var DEFINITIONS: {[any]: Definition} = { ... }
I guess this syntax doesn't exist (yet? ;) ).
Define return type of object DEFINITIONS
but have to access using a string key:
interface Definition {
id: number;
type: string;
}
var DEFINITIONS: {[key: string]: Definition} = {
v1: {
id: 4,
type: 'abc'
}
}
DEFINITIONS['v1']
Can access DEFINITIONS
using a non-string key but not define return type:
interface Definition {
id: number;
type: string;
}
var DEFINITIONS = {
v1: {
id: 4,
type: 'abc'
}
}
DEFINITIONS.v1 // Rightly does not show as having interface of `Definition`
Or laboriously:
interface Definition {
id: number;
type: string;
}
var DEFINITIONS: {v1: Definition, v2: Definition, v3: Definition, etc...} = {
v1: {
id: 4,
type: 'abc'
},
v2: { ... },
v3: { ... },
etc ...
}
DEFINITIONS.v1 // Great! Has explicit interface of Definition
// or:
var v1: Definition = {id: 4, type: 'abc'};
var DEFINITIONS2 = {v1};
p.s. I don't know what the correct technical terms for access using keys like ['v1']
or v1
is.
Upvotes: 0
Views: 709
Reputation: 18766
The indexer property of a type establishes the object as being a hash map. Intentionally, this means that you can only use the bracket notation to access properties. This is normally actually a good thing for readability because it means that there is a clear syntactic difference between a hash map created using Object versus other non-dynamic objects. However, there is also an open enhancement request to do what you are asking.
p.s. I don't know what the correct technical terms for access using keys like ['v1'] or v1 is.
The EcmaScript specification refers to these as the “bracket notation” and “dot notation”, respectively; colloquially they are often referred to as “array accessor” and “dot accessor”.
Upvotes: 1