Created
March 22, 2020 20:08
-
-
Save francoisgeorgy/4e2c32471ca170d6caae68b378966874 to your computer and use it in GitHub Desktop.
#typescript interfaces vs types
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //extending interfaces | |
| interface PartialPointX { x: number; } | |
| interface Point extends PartialPointX { y: number; } | |
| //extending types | |
| type PartialPointX = { x: number; }; | |
| type Point = PartialPointX & { y: number; }; | |
| // Interface extends type | |
| type PartialPointX = { x: number; }; | |
| interface Point extends PartialPointX { y: number; } | |
| //Type alias extends interfaces | |
| interface PartialPointX { x: number; } | |
| type Point = PartialPointX & { y: number; }; | |
| //defining the interface for objects | |
| interface Point { | |
| x: number; | |
| y: number; | |
| } | |
| //using types as well | |
| type Point2 = { | |
| x: number; | |
| y: number; | |
| }; | |
| //implementing the Interface | |
| class SomePoint implements Point { | |
| x: 1; | |
| y: 2; | |
| } | |
| //Implementing the Type alias | |
| class SomePoint2 implements Point2 { | |
| x: 1; | |
| y: 2; | |
| } | |
| type PartialPoint = { x: number; } | { y: number; }; | |
| // This is the only thing you can't do: implement a union type | |
| class SomePartialPoint implements PartialPoint { | |
| x: 1; | |
| y: 2; | |
| } | |
| // The only extra feature Interfaces bring to the table (that Type aliases don’t), | |
| // is “declaration merging” which means you can define the same interface several | |
| // times and with each definition, the properties get merged: | |
| interface Point { x: number; } //declaration #1 | |
| interface Point { y: number; } //declaration #2 | |
| // These two declarations become: | |
| // interface Point { x: number; y: number; } | |
| const point: Point = { x: 1, y: 2 }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment