Reputation: 30628
I would like to define an interface which has some known members, and unknown members should map back to the same type. I would like to be able to define:
interface Foo {
name?: string;
[others: string]: Foo;
}
This would allow me to define:
var myFoo: Foo = {
name: 'foo1'
anotherfoo: {
name: 'foo2'
yetanotherfoo: {
name: 'foo3'
}
}
}
However, my interface fails to compile with the following error message:
Property 'name' of type 'string' is not assignable to string index type 'Foo'
The only way I've managed to do this so far is to define my index type with type any:
[others: string]: any;
This allows the code to compile, but obviously loses any type safety and intellisense for the further down elements.
I do not want a suggestion to change my data structure - this is actually to correct a typescript definition for the knockout mapping library, which no longer works for TS1.6 due to not allowing undefined members.
Upvotes: 2
Views: 364
Reputation: 221282
interface Foo {
name?: string;
[others: string]: Foo;
}
The declaration is self-contradicting: it says every declared property on this type is a Foo
, but name
is a string
.
To fix, indicate that all declared properties are either string
or Foo
:
interface Foo {
name?: string;
[others: string]: Foo|string;
}
Upvotes: 3