Your problem is caused by attempting to specify the indexed type alongside "exceptions" to that type.
If you look at the below code (which should be what you are after) - if the Example
interface had the index signature, it would conflict with the other members. For example method1
doesn't conform to this: [index: string]: string;
interface Example {
classNames: { [index: string]: string; };
method1: () => void;
method2: () => void;
}
interface Example1 {
[index: string]: string;
}
type ExampleUnion = Example | Example1;
const x: ExampleUnion = {
classNames: {
foo: 'foo',
bar: 'bar'
},
method1: () => {},
method2: () => {},
stringKey1: 'stringKey1',
stringKeyN: 'stringKeyN',
}
Now this causes you issues on access, because the two interfaces are still in conflict. You could solve that with custom type guards, but a different shape would resolve all your problems in one go:
interface Example {
classNames: { [index: string]: string; };
propertyBag: { [index: string]: string; };
method1: () => void;
method2: () => void;
}
const x: Example = {
classNames: {
foo: 'foo',
bar: 'bar'
},
method1: () => {},
method2: () => { },
propertyBag: {
stringKey1: 'stringKey1',
stringKeyN: 'stringKeyN',
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…