// enum
enum Role {
ADMIN,
READ_ONLY,
AUTHOR
}
// object
type Person = {
readonly id: string | number; // readonly, cannot be re-assigned
firstName: string; // string
lastName: string; // string
fullName: (firstName: string, lastName: string ) => string; // function with two params string and returns string
age: number; // number
month: number | string; // union
hobbies: string[]; // array
childBornAt: (number | string)[]; // array of string or number
keyValuePair: [string, number]; // turple: we are sure the first element is a string and the second number
role: Role;
callback: (num: number) => void; // function that doesnt return anything
}
For objects this is preferable
interface Indexed {
readonly id: string | number;
}
interface Named {
firstName: string; // string
middleName?: string; // optional
lastName: string; // string
}
interface Greetable extends Named, Indexed {
greet: (name: string) => string
}
// use it like so
const Manel: Greetable = {
id: 123,
firstName: 'Manel',
lastName: 'Paiva',
greet: (name) => `Hello ${name}`
}
Can also be used for function types
interface AddFn {
(a: number, b: number): number
}
const add : AddFn = (a, b) => a + b
type Admin = {
name: string
priviliges: string[]
}
type Employee = {
name: string
startDate: Date
}
// in objects combines them
type ElevatedUser = Employee & Admin
const admin: ElevatedUser = {
name: 'Joao',
priviliges: ['delete users'],
startDate: new Date()
}
type Combinable = string | number
type Numeric = number | boolean
// in union types intersects whats in common
type Universal = Combinable & Numeric // number
function add(a: Combinable, b: Combinable) {
// check if its a string before adding
if (typeof a === 'string' || typeof b === 'string') {
return a.toString() + b.toString()
}
return a + b
}
Objects
type UnknownEmployee = Employee | ElevatedUser
function printEmployeeInformation(emp: UnknownEmployee) {
console.log('Name: ', emp.name)
// check if the UnknownEmployee has the priviliges key
if ('priviliges' in emp) {
console.log('Privileges: ', emp.priviliges)
}
}
Class instances
class Car {
drive() {
console.log('Driving...')
}
}
class Truck {
drive() {
console.log('Driving...')
}
loadCargo(ammount: number): void {
console.log('Loading: ', ammount)
}
}
type Vehicle = Car | Truck
const mercedez = new Car()
const man = new Truck()
function useVehicle(vehicle: Vehicle) {
vehicle.drive()
// check if the vehicle is an instance of truck
if (vehicle instanceof Truck) vehicle.loadCargo(2000)
}