1/**
2* Modern Typescript types and interfaces are both very powerful (2020)
3* It is almost down to personal choice, these days.
4* Key differences:
5 - The type alias can also be used for other types such as primitives,
6 unions, and tuples.
7 - Unlike a type alias, an interface can be defined multiple times,
8 and will be treated as a single interface
9* Decision on when to use:
10 - Personally, I use the interface to make it clear that it
11 is intended to be implemented and types for everything else.
12*/
13
14// type
15type Person = {
16 name: string;
17 age: number;
18}
19
20type speak = (sentence: string) => void;
21
22// interface
23interface Person extends Human {
24 name: string;
25 age: number;
26}
27
28interface speak {
29 (sentence: string): void;
30}
1// Types are used to enforce the data type of a variable
2// For example:
3
4type Weekday = 'Monday' | 'Tuesday' | 'Wednesday' | 'Thursday' | 'Friday' | 'Saturday' | 'Sunday';
5
6let day1: Weekday = 'Monday'; // OK
7let day2: Weekday = 'January'; // ERROR: 'January' is not assignable to type 'Weekday'
8
9// Interfaces are used to enforce the shape of an object
10// For example:
11
12interface Person {
13 firstName: string;
14 lastName: string;
15 age: number;
16}
17
18// OK
19let person1: Person = {
20 firstName: 'James',
21 lastName: 'Smith',
22 age: 30
23}
24
25// ERROR: property 'age' is missing
26let person2: Person = {
27 firstName: 'Mary',
28 lastName: 'Williams'
29}
30
31// NOTE: Technically, you can use types to enforce the shape of objects,
32// but that's not what they are intended for.
33
34// More details: https://www.typescriptlang.org/docs/handbook/advanced-types.html
1// for starters:
2// interfaces and types are very similar, they just differ in syntax
3
4// interface
5interface Car {
6 name: string;
7 brand: string;
8 price: number;
9}
10
11// type
12type Car = {
13 name: string;
14 brand: string;
15 price: number;
16}
17
18// interface
19interface Car extends Vehicle {
20 name: string;
21 brand: string;
22 price: number;
23}
24
25// type
26type Car = Vehicle & {
27 name: string;
28 brand: string;
29 price: number;
30}