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
Output
If the indexer return type is 'any' then properties can return any types:
with-members3.ts
Output
最后更新于