Answer the question
In order to leave comments, you need to log in
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
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;
}
class Tomato implements IVegetable {
name: string = 'Tomato';
getCalories() {
return 18;
}
}
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.
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 questionAsk a Question
731 491 924 answers to any question