type Admin = {
name: string;
privileges: string[];
};
type Employee = {
name: string;
startDate: Date;
};
type ElevatedEmployee = Admin & Employee;
const el: ElevatedEmployee = {
name: "Max",
privileges: ["create-server"],
startDate: new Date()
};
interface Admin {
name: string;
privileges: string[];
};
interface Employee {
name: string;
startDate: Date;
};
interface ElevatedEmployee extends Employee, Admin {};
const el: ElevatedEmployee = {
name: "Max",
privileges: ["create-server"],
startDate: new Date()
};
type Combinable = string | number;
type Numeric = number | boolean;
type universal = Combinable & Numeric; // number 형식이 교집합이므로 number만 할당 가능하다.
// const test: universal = "test"; // number 형식이 아니라는 에러 발생
const test: universal = 10;
type Combinable = string | number;
function add(a: Combinable, b: Combinable) {
if (typeof a === "string" || typeof b === "string") { // typeof 타입가드
return a.toString() + b.toString();
}
return a + b;
}
type Admin = {
name: string;
privileges: string[];
};
type Employee = {
name: string;
startDate: Date;
};
type UnknownEmployee = Admin | Employee;
const el: Admin = {
name: "Max",
privileges: ["create-server"],
};
function printEmployeeInfo(emp: UnknownEmployee) {
console.log(`Name: ${emp.name}`);
// if(typeof emp === "Employee") -> 불가능하다.
if ("privileges" in emp) {
console.log(`Privileges: ${emp.privileges}`);
}
if ("startDate" in emp) {
console.log(`StartDate: ${emp.startDate}`);
}
}
printEmployeeInfo(el); //Name: Max Privileges: create-server
class Car {
drive() {
console.log("Driving a car...");
}
}
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(100);
}
}
useVehicle(v1); // Driving a car...
useVehicle(v2); // Driving a truck... / Loading cargo 100
interface Bird {
type: "bird"; // 공통의 리터럴 타입 프로퍼티
flyingSpeed: number;
}
interface Horse {
type: "horse"; // 공통의 리터럴 타입 프로퍼티
runningSpeed: number;
}
type Animal = Bird | Horse;
function moveAnimal(animal: Animal) {
let speed;
switch (animal.type) {
case "bird":
speed = animal.flyingSpeed;
break;
case "horse":
speed = animal.runningSpeed;
break;
}
console.log(`Moving at speed: ${speed}`);
}
// moveAnimal({type:"bird", runningSpeed: 5}) // Bird 형식에서는 runningSpeed를 쓸 수 없다고 에러남
moveAnimal({ type: "bird", flyingSpeed: 5 }); // Moving at speed: 5
// TS가 inputElement가 input태그라는 것을 추론 못하고 HTMLElement || null 이라고 인식한다.
const inputElement = document.getElementById("user_input");
// TS는 inputElement의 존재를 확신하지 못하기 때문에 inputElement에서부터 에러가 발생한다.
inputElement.value = "Hi";
▽▽▽
// 개발자가 null로 반환하지 않겠다고 정해줘도(!) HTMLElement에는 value라는 속성이 없다고 에러가 난다.
const inputElement = document.getElementById("user_input")!;
inputElement.value = "Hi";
▽▽▽
// 개발자가 inputElement라고 타입을 지정해주면 더이상 에러가 나지 않는다.
const inputElement = <HTMLInputElement>document.getElementById("user_input")!;
inputElement.value = "Hi";
OR
// 리액트에서 볼 수 있는 JSX와의 충돌의 막기 위해 아래와 같이 표기도 가능하다.
const inputElement = document.getElementById("user_input")! as HTMLInputElement;
inputElement.value = "Hi";
▽▽▽
// null을 반환할 가능성이 있다면 아래와 같이 작성한다.
const inputElement = document.getElementById("user_input");
if (inputElement) {
// HTMLInputElement과 value가 붙으면 안되니까 ()로 감싼다.
(inputElement as HTMLInputElement).value = "Hi";
}
interface ErrorContainer {
[prop: string]: string;
}
const errorBag = {
email: "Not a valid email",
username: "Must start with a capital character"
}
type Combinable = string | number;
function add(a: Combinable, b: Combinable) {
if (typeof a === "string" || typeof b === "string") {
return a.toString() +" "+ b.toString();
}
return a + b;
}
const actress1 = add("Keira", "Knightley");
actress1.split(" "); // TS는 Combinable을 타입으로 받아들이기 때문에 string이라고 확신하지 못해서 에러가 난다.
▽▽▽
type Combinable = string | number;
function add(a: number, b: number): number;
function add(a: string, b: string): string;
function add(a: Combinable, b: Combinable) {
if (typeof a === "string" || typeof b === "string") {
return a.toString() + " " + b.toString();
}
return a + b;
}
const actress1 = add("Keira", "Knightley");
const splitedName = actress1.split(" "); // TS는 Combinable을 타입으로 받아들이기 때문에 string이라고 확신하지 못해서 에러가 난다.
console.log(splitedName); // ['Keira', 'Knightley']
const userData = {
id: 1,
name: "Max",
//job: { title: "CEO", description: "Own a company" },
};
console.log(userData.job?.description);
const userInput = null;
console.log(userInput ?? "No data"); // No data