Issue
What is the difference between these statements (interface
vs type
) in TypeScript?
interface X {
a: number
b: string
}
type X = {
a: number
b: string
};
Solution
Update March 2021: The newer TypeScript Handbook has a section Interfaces vs. Type Aliases which explains the differences.
Original Answer (2016)
As per the (now archived) TypeScript Language Specification:
Unlike an interface declaration, which always introduces a named object type, a type alias declaration can introduce a name for any kind of type, including primitive, union, and intersection types.
The specification goes on to mention:
Interface types have many similarities to type aliases for object type literals, but since interface types offer more capabilities they are generally preferred to type aliases. For example, the interface type
interface Point { x: number; y: number; }
could be written as the type alias
type Point = { x: number; y: number; };
However, doing so means the following capabilities are lost:
An interface can be named in an extends or implements clause, but a type alias for an object type literal cannotNo longer true since TS 2.7.- An interface can have multiple merged declarations, but a type alias for an object type literal cannot.
Answered By - Binary Birch Tree
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.