In fact, the two are very similar, interface can do, type can do almost everything. But there are still some differences, which is what this article is trying to describe.

Interface can only represent the type of the object structure. If you want to represent the primitive type of JS (undefined, null, Boolean, string, number), you can only refer to the type:

type A = string
Copy the code

Type can also represent an object type

type Reptile = {
    genus: string
}
Copy the code

Second, type can evaluate properties dynamically.

In interface, we can represent an object like this:

interface Y {
    [k: string] :number
}
Copy the code

K can be of type string or number, but only one or the other.

Type is more powerful in this respect, and it can use computed attributes. In the following example, X contains two attributes: ‘xiao Wang’ and ‘xiao wen’.

type Keys = "Wang" | "Essays"

type X = {
  [key in Keys]: string
}

const test: X = {
    'wang': 'Muscle man'.'xiaowen': 'Muscle man too'
}
Copy the code

Interface does not support this notation:

The following is an error message:

Of course, the following combination type is not supported either:

type Keys = "Wang" | "Essays"

type X = {
  [key in Keys]: string
}

type XX = keyof Keys;

interface Y {
    [k: XX]: number
}

Copy the code

Third, the type declarations of type cannot have the same name, and the renames of interface declarations are merged together

For example, the following is an error:

You can look at this online example

With this feature, when we want to mount some custom properties to the global window property, we can use interface:

interface Window {
    xxx: string;
}
Copy the code

So far I’ve summarized the three differences above, but some of the other differences are related to error message presentation, so I won’t list them if they are not very important. They’re very, very similar. Generally speaking, we can always use one according to the habit, and then consider switching to another when we encounter problems, also don’t need too much entanglement. hope to help students with choice anxiety 🙂

Thanks for reading, scatter flowers!