Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Typescript throw an error on the interface but not on the type? [duplicate]

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?

like image 709
Duannx Avatar asked Oct 16 '25 01:10

Duannx


1 Answers

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

like image 172
wonderflame Avatar answered Oct 18 '25 13:10

wonderflame



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!