“This is the 11th day of my participation in the First Challenge 2022. For details: First Challenge 2022.”
There are two confusing concepts in typescript: Type and interface. Both of them can be used to represent interfaces, but there are some differences between them in practice. In this article, we will take a look at the two concepts and thoroughly understand their differences.
Type is the same as interface
In my opinion, they are two different forms of interface definition, both for the same purpose, to define the shape of an object or function, as shown in the following example
interface example {
name: string
age: number
}
interface exampleFunc {
(name:string,age:number): void
}
type example = {
name: string
age: number
}
type example = (name:string,age:number) = > void
Copy the code
They also support inheritance, and they are not independent, but can inherit from each other, but in a slightly different form
type exampleType1 = {
name: string
}
interface exampleInterface1 {
name: string
}
type exampleType2 = exampleType1 & {
age: number
}
type exampleType2 = exampleInterface1 & {
age: number
}
interface exampleInterface2 extends exampleType1 {
age: number
}
interface exampleInterface2 extends exampleInterface1 {
age: number
}
Copy the code
You can see that for interfaces, inheritance is implemented through extends, while for type, inheritance is implemented through &, which can also be called a cross type
Differences between Type and interface
Let’s start by talking about what type can do that interface can’t
- Type can be definedAlias for the base type, such as
type myString = string
- Type can be passedtypeofOperator, as in
type myType = typeof someObj
- Type can be declaredThe joint type, such as
type unionType = myType1 | myType2
- Type can be declaredA tuple type, such as
type yuanzu = [myType1, myType2]
Let’s talk about what interface can do, but type can’t
-
Interfaces can be declared merged as shown in the following example
interface test { name: string } interface test { age: number } /* test is {name: string age: number} */ Copy the code
In this case, if it is type, it will override, and only the last type will always be in effect
conclusion
In typescript, there are many confusing concepts such as extends and implements, as well as more advanced concepts such as generics. These are all must-know things in TS, so be sure to dig into them
While TS brings robustness to our code, it also introduces more concepts and knowledge that we need to keep learning. In the future, I also plan to output more articles about TS to deepen my understanding of TS and help my friends who like to read my articles. Ok, I will write it here, over!