An Interest In:
Web News this Week
- April 1, 2024
- March 31, 2024
- March 30, 2024
- March 29, 2024
- March 28, 2024
- March 27, 2024
- March 26, 2024
Learn about difference between Type & Interface in Typescript
If you are using typescript, you might use interface & type but if I ask you the difference between them, are you able to answer it ?
At the end of this article, you will be able to answer it during any discussion or interview !
Type
The basic, it allow us to create a new type !
Interface
In contrary to type
, interface
is restricted to an object type.
With the news release, type
and interface
are similar but there some differences between them.
Similitude
Object typing
You can define the shape of an object with both, but the syntax is not the same
with interface:
interface A { a: number}const a: A = { a: 5 }
with type:
type A = { a: number}const a: A = { a: 5 }
Extend
Both can be extended, and the difference is ... yes the syntax again !
with interface:
interface A { a: number}interface AB extends A { b: number}const ab: AB = { a: 5, b: 6 }
with type:
type A = { a: number}type AB = A & { b: number }const a: AB = { a: 5, b: 6 }
The difference
What type can do, and what interface cant do
Unlike interface
, type
can be used for creating new type with union, tuples or can be used to defined primitive type !
type A = string | number // uniontype Primitive = string | boolean | number | null | interface | symbol // Create a new type from primitives typetype DataTuple = [number, string] // tuple typing
What interface can do, and what type cant do
A class
can implement
an interface
interface A { a: number}class Toto implements A { a = 55}
Interface can be merged in a single interface
if there are defined multiple times
interface Toto { a: number}interface Toto { b: number}const toto: Toto = { a: 55, b: 66,}
Conclusion
As you can see type
& interface
are very similar but each other have his own dedicated feature !
I personally use interface when I need to type object structure, and I use type when I need to create type from primitive type or when I want to combine other types in one type !
Original Link: https://dev.to/codeozz/learn-about-difference-between-type-interface-in-typescript-1nif
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To