index signature
Indexer with other members
Besides indexers, indexable interfaces allow to add additional properties
When using positional indexer (i.e. indexer of number type) we can define array properties/methods which need to be exposed.
with-members.ts
interface States{
[index: number]: boolean;
length: number;
pop(): boolean;
}
let s: States = [true, false, true];
console.log(s);
console.log(s.length);
console.log(s.pop());
console.log(s);
Output
[ true, false, true ]
3
true
[ true, false ]
When using indexer of string type all properties should return the same type that the indexer returns
with-members2.ts
interface States {
[state: string]: boolean;
mainScreen: boolean;
//following not allowed
//screenName: String;
}
let s: States = {mainScreen: false};
s["enabled"] = true;
s["maximized"] = false;
console.log(s);
Output
{ mainScreen: false, enabled: true, maximized: false }
If the indexer return type is 'any' then properties can return any types:
with-members3.ts
interface States {
[state: string]: any;
screenName: String;
}
let s: States = {screenName:"main"};
s["enabled"] = true;
s["maximized"] = false;
s["width"]=300;
s["height"]=200;
console.log(s);
Output
{ screenName: 'main',
enabled: true,
maximized: false,
width: 300,
height: 200 }
最后更新于