M
M
Max Zhukov2018-07-04 17:53:13
typescript
Max Zhukov, 2018-07-04 17:53:13

What is the difference between type and interface. In what cases what to use?

What is the difference between type and interface. In what cases what to use?
Google is not entirely clear to me.

Answer the question

In order to leave comments, you need to log in

5 answer(s)
M
m019m1, 2019-11-21
@m019m1

5dd67a8468750709387302.jpeg

E
Evgeny, 2018-07-04
Maltsev @maltsever

Hey! Roughly speaking, the interface only describes the functionality. And the class that implements this interface must specifically define the functionality. For example:

interface IVegetable {
    name: string;
    getCalories(): number;
}

And the concrete class:
class Tomato implements IVegetable {
    name: string = 'Tomato';
    getCalories() {
       return 18;
    }
}

Type is just a typing of some variable, usually non-standard. For example, we want to define a type that will describe the degree of readiness of steaks: Thus, we can assign only these predefined values ​​\u200b\u200bto a SteakRoast type variable, otherwise Typescript will scream due to type mismatch.

Y
Yuri Efremochkin, 2019-09-24
@merkuriy

Useful links discussing the difference between Interfaces (the interface keyword) and Type Aliases (the type keyword):
This will be useful for those interested in this issue and will allow you to study the topic in more depth.

R
Roman Yakovlev, 2021-02-04
@feligz

There are 2 main differences between Type alias and Interface (as of TS 4.1.3).
1. You cannot use implements if the union operator is present.
typeBox = shape | Figure
class MyBox implements Box {} - error...
2. One name cannot be used for more than one type. In other words, you can't extend a type, but you can extend an interface (and this can be handy if you need to extend the interface of a third-party library).
type Box = {}
type Box= {x: number} - error...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question