I don't know why Typescript throws an error when using the interface but works fine with type. Please consider this code:
const fn = (a: { [key: string]: number | string }) => {
console.log(a)
};
interface FooInterface {
id: number;
name: string;
}
type FooType = {
id: number;
name: string;
}
const fooInterface: FooInterface = { id: 1, name: 'name' };
const fooType: FooType = { id: 1, name: 'name' };
fn(fooType);
fn(fooInterface); <-- error here
Playground link
The Typescript will throw an error with the line fn(fooInterface);
. It says:
Argument of type 'FooInterface' is not assignable to parameter of type '{ [key: string]: string | number; }'.
Index signature for type 'string' is missing in type 'FooInterface'.
Why does the error happen and why does it only happen with the interface?
Interfaces do not have an implicit index signature, and that's why you can't pass the interface. If you would add the index signature, the error will disappear:
interface FooInterface {
id: number;
name: string;
[a: string]: string | number;
}
The reason behind this is that interfaces can be augmented with declaration merging, whereas it is not possible with types.
Related issue: Typescript#15300
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With