2

I hear that type and interface only have different when you want using things like & or extends, but......

Why

interface ITest {
  a: boolean;
}
const Itest: ITest = { a: true };
const test: { [index: string]: boolean } = Itest;

cant pass compile, while

type TTest = {
  a: boolean,
};
const Ttest: TTest = { a: true };
const test: { [index: string]: boolean } = Ttest;

have not?

饕餮饗食
  • 105
  • 1
  • 5
  • See [my answer](https://stackoverflow.com/questions/37233735/interfaces-vs-types-in-typescript#answer-64971386) answer. The difference in indexing. Interfaces are not indexed by the default (tis makes them safer), whereas `types` are indexed. Also, see [my article](https://catchts.com/safer-types#part_2) about using `types` and `interfaces` – captain-yossarian from Ukraine Oct 28 '22 at 06:49

1 Answers1

0

Interfaces are basically a way to describe data shapes, for example, an object. Type is a definition of a type of data, for example, a union, primitive, intersection, tuple, or any other type.

There is an object definition here, so Interface must be used.

My personal opinion: Try to use Interface as much as possible instead of Type.

Furkan Gulsen
  • 1,384
  • 2
  • 12
  • 24
  • I don't see how this addresses the question as asked. A type alias can indeed be an object type, as shown above via `type Test = {a: boolean}`. What do you mean by "Interface must be used"? The underlying issue has to do with implicit index signatures and is discussed in [microsoft/TypeScript#15300](https://github.com/microsoft/TypeScript/issues/15300), and this answer doesn't seem to apply. – jcalz Oct 28 '22 at 13:48