Below is a sample code that has been checked by TypeScript playground https://www.typescriptlang.org/play/
interface PartialCustomData {
option?: number;
}
interface A {
[key: string]: string | PartialCustomData;
}
interface B extends A {
[key: string]: string | PartialCustomData | {[key: string]: string};
}
// No error with this implementation
const b: B = { key1: 'a', key2: {b: 'b'}};
const a: A = b;
// Error occurs here
const _a: A = { key1: 'a', key2: {b: 'b'}}
In the case of const a: A = b;
, there is no error.
However, in
const _a: A = { key1: 'a', key2: {b: 'b'}}
, an error is triggered.
The error message states:
Type '{ b: string; }' is not assignable to type 'string | PartialCustomData'.
Object literal may only specify known properties, and 'b' does not exist in type 'PartialCustomData'.(2322)
input.ts(6, 5): The expected type comes from this index signature.
Why doesn't the error occur at const a: A = b;
?