간단 예시
const name : string = 'NAME';
const arr : array [number] = [1, 2, 3];
interface User {
name : string;
age : number;
}
Const user : User = {
name : 'xx',
age :
}
function hello(name?: string) {
return `hello, ${name || "world}`;
}
console.log(hello("Sam"));
let direction: "left" | "right" | "up" | "down";
direction = "left"; // 가능
direction = "right"; // 가능
// direction = "forward"; // 오류 발생 (지정된 리터럴 외의 값)
let value = string | number;
value = "Hello"; // 문자열 할당 가능
value = 42; // 숫자 할당 가능
interface Person {
name: string;
}
interface Employee {
employeeId: number;
}
type EmployeePerson = Person & Employee;
const employee: EmployeePerson = {
name: "Alice",
employeeId: 123
};
interface GenericMobile<T> {
name: string;
age: number;
option: T;
}
// T가 string이면 해당 T 제네릭 타입의 프로퍼티는 string 타입이어야한다.
const m1: GenericMobile<string> = {
name: 'm1',
age: 10,
option: 'string',
};
// T가 object이면 해당 T 제네릭 타입의 프로퍼티는 object 타입이어야한다.
const m3: GenericMobile<object> = {
name: 'm3',
age: 12,
option: {
color: 'red',
price: 1000,
},
};
// object타입인 제네릭타입의 경우 명시적으로 객체 그 자체의 부분 명시 또한 가능하다.
const m4: GenericMobile<{ color: string; price: number }> = {
name: 'm4',
age: 13,
option: {
color: 'blue',
price: 1000,
},
};
Tip>
type : 리터럴 형태로 구현할 때 사용하기 용이하다.
interface : 객체 형태로 구현할 때 사용하기 용이하다.