typeof [객체] === '[타입]'
[메소드 이름 or 프로퍼티 이름] in [객체]
[클래스] instanceof [메소드 이름 or 프로퍼티 이름]
typeof, in, instanceof 타입 가드를 사용할 수 있다.
인터페이스는 자바스크립트로 컴파일되지 않으니 instanceof 를 사용할 수 없다.
type Admin = {
name: string;
privileges: string[];
};
type Employee = {
name: string;
startDate: Date;
};
// interface ElevatedEmployee extends Admin, Employee {}
type ElevatedEmployee = Admin & Employee;
const e1: ElevatedEmployee = {
name: 'Max',
privileges: ['create-server'],
startDate: new Date()
}
type Combinable = string | number;
type Numeric = number | boolean;
type Universal = Combinable & Numeric;
function add2(a: Combinable, b: Combinable) {
if (typeof a === 'string' || typeof b === 'string') {
return a.toString() + b.toString();
}
return a + b;
}
type UnknownEmployee = Employee | Admin;
function printEmployeeInformation(emp: UnknownEmployee) {
console.log('Name: ' + emp.name);
if ('privileges' in emp) {
console.log('Privileges: ' + emp.privileges);
}
if ('startDate' in emp) {
console.log('StartDate: ' + emp.startDate);
}
}
printEmployeeInformation({ name: 'a', startDate: new Date() });
class Car {
drive() {
console.log('Driving...');
}
}
class Truck {
drive() {
console.log('Driving a truck...');
}
loadCargo(amount: number) {
console.log('Loading cargo ... ' + amount);
}
}
type Vehicle = Car | Truck;
const v1 = new Car();
const v2 = new Truck();
function useVehicle(vehicle: Vehicle) {
vehicle.drive();
if (vehicle instanceof Truck) {
vehicle.loadCargo(1000);
}
}
useVehicle(v1);
useVehicle(v2);