32
loading...
This website collects cookies to deliver better user experience
type
or interface
. For that reason, understanding both well will make your TypeScript better quickly.interface
is used just to define the shape of objects, type
has other use cases.type Pet = 'Cat' | 'Dog'
type CoolNumbers = 3.1416 | 4 | 100
interface DesktopFile {
icon: string;
}
interface DesktopFile {
extension: string;
}
// Error: Property 'icon' is missing in type '{ extension: string; }'
// but required in type 'DesktopFile'.
const file: DesktopFile = {
extension: 'pdf',
}
Type
would result in an error.type File = {
kind: 'file';
name: string;
extension: string;
}
type Folder = {
kind: 'folder';
name: string;
filesInside: number;
}
type DesktopItem = File | Folder
const item: DesktopItem = {...}
if (item.kind === 'file'){
// TypeScript knows that the properties
// of the type File are defined here
}
instanceof
in other languages.type Vehicle = {
kind: 'motorcycle' | 'car'
numberOfWheels: number
numberOfAirbags: number | undefined
}
const vehicle: Vehicle = {...}
if (vehicle.kind === 'car'){
// TypeScript still thinks that
// numberOfAirbags could be undefined
}
Car
properties are available.type
and interface
.interface Cat {
name: string;
whiskersLength: number;
}
const cat: Cat = {
name: 'Uxia',
whiskersLength: 6,
bestFriend: 'Nina',
// ~~~~~~~~~~~~~~~~~~ Object literal may only specify known properties,
// and 'bestFriend' does not exist in type 'Cat'
};
Cat
.type Person = {
name: string;
zipCode?: string;
}
const randomGuy: Person = {
name: 'Pedro',
zip: '45420',
}
type
easier to reason about and more readable. type Flyable = {
fly(): void;
}
type Airplane = Flyable & {
...
}
interface Helicopter extends Flyable {
...
}