typescript
λ₯Ό μ΄μ©ν΄ κ°λ°νλ€λ³΄λ©΄ νμ κ³ λ―Όνκ² λλ λΆλΆμ΄ μλ€. λ°λ‘ type
κ³Ό interface
μ€ μ΄λκ²μ μ¬μ©ν΄μ νμ
μ μ μν΄μ€κΉ λΌλ λ¬Έμ μ΄λ€.
μ°μ λκ°μ§ λͺ¨λ λΉμ·ν λ°©μμΌλ‘ λμνλ€. μ¬μ©μκ° νμ
μ μ μΈνκ³ κ·Έ μ΄λ¦μ μ§μ΄μ£Όλ κ²μ΄ 곡ν΅μ μΈ κΈ°λ₯μ΄λ€.
interface Student {
name: string;
grade: number;
hobby: string;
};
type Student = {
name: string;
grade: number;
hobby: string;
};
κ·Έλ¦¬κ³ λ λͺ¨λ νμ₯μ΄ κ°λ₯νλ€. type
μ κ²½μ° &
μ°μ°μλ₯Ό μ¬μ©νκ³ , interface
λ extends
λ₯Ό μ¬μ©ν΄ νμ₯μν¬ μ μλ€. κ°μ μ’
λ₯λ€ λΏλ§ μλλΌ λμ μλ‘μλ‘ &
μ extends
λ₯Ό μ¬μ©ν΄ νμ₯μ΄ κ°λ₯νλ€.
interface School extends Student {
teacher: string;
study: string;
};
type School = {
teacher: string;
study: string;
} & Student;
κ·ΈλΌ μ΄μ μ°¨μ΄μ μ 보λλ‘ νμ.
첫λ²μ§Έλ‘ type
μ primitive
, union
, tuple
μ μ μν μ μμ§λ§ interface
μ κ²½μ° λΆκ°λ₯νλ€.
type Something = number; // primitive type
type StringOrNumber = string | number; // union type
type Grade = [number, number]; // tuple
λλ²μ§Έλ‘ interface
μ κ²½μ° κ°μ λͺ
μΉμ μ¬μ©νμμλ μλμΌλ‘ merged
λμ§λ§(Declaration Merging
) type
μ κ·Έλ μ§ μλ€. (μ΄κ²μ λλ μ νν μμ§ λͺ»νλ λΆλΆμ΄λ€)
interface User {
name: string;
};
interface User {
id: number;
};
const new_user: User = {
id: 1234,
name: 'Sam'
};
// new_user.id; >> 1234
// new_user.name >> Sam
type User = {
name: string;
};
type User = { // >> Duplicate identifier 'User' (ts2300)
id: number;
};
λ§μ§λ§μΌλ‘ type
, interface
μ λν λͺκ°μ§ μ¬μ© μλ리μ€λ₯Ό 보면 λ€μκ³Ό κ°μ κ²μ΄λ€.
type
primitive type
μ λν νμ μ μtuple type
μ λν νμ μ μfunction type
μ λν νμ μ μunion type
μ λν νμ μ μmapped type
μ λν νμ μ μ
interface
declaration merge
κΈ°λ₯μ νμ©ν΄μΌ ν λ (λ³΄ν΅ μΈλΆμ 곡κ°νapi
λinterface
λ₯Ό μ¬μ©ν΄ νμ₯μ±μ λμΈλ€)- κ°μ²΄λ₯Ό μ μνκ±°λ
type
μ μ¬μ©ν νμκ° μμλ
Typescript
νμ κ°λ₯ν interface
λ₯Ό μ¬μ©νκ³ , union
λλ tuple
μ λν μ μκ° νμν λλ type
μ μ¬μ©νλλ‘ κΆμ₯νκ³ μλ€. νμ§λ§ νλ‘μ νΈμ κ°λ° 컨벀μ
μ λ°λΌ μ μ νκ² μ¬μ©νλ©΄ νΉλ³ν μΌμ΄μ€κ° μλ μ΄μ ν¬κ² λ¬Έμ λ κ²μ μλ€κ³ μκ°νλ€.
- https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#differences-between-type-aliases-and-interfaces