ref – https://pawelgrzybek.com/typescript-interface-vs-type/
Interfaces are restricted to an object type
Interface declarations can exclusively represent the shape of an object-like data structures. Type alias declarations can create a name for all kind of types including primitives (undefined, null, boolean, string and number), union, and intersection types. In a way, this difference makes the type more flexible. In theory every type declaration that you can express with an interface, you can recreate using a type alias. Lets have a look at an example that can be represented using a type alias but is beyond the power of an interface.
1 |
type info = string | { name: string }; |
You can merge interfaces but not types
Multiple declarations with the same name are valid only when used with interface. Doing so doesn’t override previous one but produces a merged result containing members from all declarations.
1 2 3 4 5 6 7 8 9 10 11 12 |
interface DudeInterface { name: string; } interface DudeInterface { age: number; } const pawel: DudeInterface = { name: "Pawel Grzybek", age: 31 }; |
Type aliases can use computed properties
The in keyword can be used to iterate over all of the items in an union of keys. We can use this feature to programmatically generate mapped types. Have a look at this example using type aliases.
1 2 3 4 5 6 7 8 9 10 |
type Keys = "firstname" | "surname" type DudeType = { [key in Keys]: string } const test: DudeType = { firstname: "Pawel", surname: "Grzybek" } |
Unfortunately we cannot take advantage of computed properties in an interface declaration.
resolution of both (types and interfaces) happens in the same phase. No more circular references
1 2 3 4 5 6 7 8 |
type Dude = string | Pals; interface Pals extends Array<Dude> {} const a: Dude = "haha"; console.log(a); // "haha" const b: Pals = [a]; console.log(b); // ["haha"] |
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
type User = { id: number; email: string; first_name: string; }; type GetUsersResponse = { // type data: User[]; }; function axiosGet () { return { title: "mr", address: "east norwood", } } const response : GetUsersResponse = axiosGet(); |
Solution is we need to make sure axiosGet returns at least a subset of properties that matches type GetUsersResponse.
In our case, it is data: User[]
1 2 3 4 5 6 7 8 9 10 11 12 13 |
function axiosGet () { const userA: User = { id: 5, email: "rtsao@uci.edu", first_name: "ricky" } return { title: "mr", address: "east norwood", data: [userA] } } |