ํฐ์คํ ๋ฆฌ ๋ทฐ
ํ์ ์คํฌ๋ฆฝํธ์์ ํ์ ์ ์ ์ธํ๋ ๋ฐฉ์์ธ interface์ type.
interface๋ ์ฌ๋ฌ ํ ๋น์ด ๊ฐ๋ฅํ๋ค.
ํ์ง๋ง ์ํ์์๊ฐ ์์ผ๋ฉฐ ์์ฃผ ์ฐ์ด์ง๋ ์๋ ๋ฏ ํ๋ค.
interface Todo {
id: string;
title: string;
completed: boolean;
};
interface Todo {
timestamp: number;
};
์์ ๊ฐ์ด interface๋ ์ฌ๋ฌ ํ ๋น์ด ๊ฐ๋ฅํ๋ค.
์ด๋ฐ ์์ผ๋ก ํ ๋นํ๊ฒ ๋๋ฉด ๊ฒฐ๊ตญ Todo์๋ 4๊ฐ์ ํ์ ์ด ๊ฐ๋ฅํ๋ค.
ํ์ธ์ ์๋ ์ฌ์ง์์ ๋ณผ ์ ์๋ฏ์ด todo. ์ ์ฐ์ผ๋ฉด ๋ด๋ถ ํ์ ํ์ธ์ด ๊ฐ๋ฅํ๋ฉฐ timestamp ํ์ ์ ํฌํจํ๊ณ ์๋ค.

๋ค๋ง, ์ด๋ ๊ฒ ์ฐ์ธ๋ค๋ฉด Todo ์์ฒด์ ํ์ ์ด ๋ณํ๊ฒ ๋๋ค.
์ฆ, ์ฒ์ ํ ๋นํ {id, title, completed} ํ์ ๋ง์ Todo๋ฅผ ํ์ฉํ๊ณ ์๋ ๊ณณ์ด ์๋ค๋ฉด
timpstamp๊ฐ ์ถ๊ฐ๋์ด ํน์ฌ๋ ์ค๋ฅ๊ฐ ๋ฐ์ํ ์๋ ์๋ค.
(๋ฆฌ์กํธ์์ push๋ฅผ ์ฌ์ฉํ ๋ ์๋ณธ ๋ฐฐ์ด์ด ๋ณํด์ ๋ถ๋ณ์ฑ์ด ๊นจ์ง๋ ๊ฒ๊ณผ ๋น์ทํ๊ฒ ์๊ฐํ๋ฉด ๋๋ ค๋..?)
๋ฐ๋ผ์ interface๋ extends, type์ & ์ฐ์ฐ์๋ฅผ ์ฌ์ฉํด์ ๋ ๊ฐ ์ด์์ ํ์ ์ ํฉ์น ์ ์๋ค.
๐interface
- interface C๊ฐ A์ B๋ฅผ ์์(extends) ํด์ ๋ชจ๋ ์์ฑ์ ๊ฐ์ง
- interface๋ ์๋์ผ๋ก ๋ณํฉ(Declaration Merging) ๊ฐ๋ฅ
// interface - extends
interface A {
name: string;
}
interface B {
age: number;
}
// B๊ฐ A๋ฅผ ํ์ฅ (interface๋ extends ์ฌ์ฉ)
interface C extends A, B {
gender: string;
}
const person: C = {
name: "์ ๋ฆฌ",
age: 25,
gender: "์ฌ์ฑ",
};
๐type
- type C๋ A, B๋ฅผ ๋ณํฉ(& ์ฐ์ฐ์ ์ฌ์ฉ)
- type์ ํ์ฅํ ๋ & ์ฐ์ฐ์๋ฅผ ์ฌ์ฉํด์ผ ํจ
// type - & ์ฐ์ฐ์
type A = {
name: string;
};
type B = {
age: number;
};
// ๋ ๊ฐ์ ํ์
์ & ์ฐ์ฐ์๋ก ํฉ์น๊ธฐ
type C = A & B & { gender: string };
const person: C = {
name: "์ ๋ฆฌ",
age: 25,
gender: "์ฌ์ฑ",
};
๐interface vs type ์ฐจ์ด

// interface ์๋ ๋ณํฉ ๊ฐ๋ฅ
interface A {
name: string;
}
interface A {
age: number;
}
const person: A = { name: "์ง์ฑ", age: 25 }; // ์๋ ๋ณํฉ๋จ
// type์ ์ค๋ณต ์ ์ธ ๋ถ๊ฐ๋ฅ โ
type B = { name: string };
type B = { age: number }; // Error: Duplicate identifier 'B'
โจ์ธ์ ์ฌ์ฉํด์ผ ํ ๊น?
- ๊ฐ์ฒด์ ๊ตฌ์กฐ๋ฅผ ์ ์ํ๊ณ ํ์ฅํ ๊ฐ๋ฅ์ฑ์ด ์๋ค๋ฉด? → interface (์๋ ๋ณํฉ ๊ฐ๋ฅ)
- ์ ๋์จ(|)์ด๋ ํํ ๊ฐ์ ๋ณต์กํ ํ์ ์กฐํฉ์ด ํ์ํ๋ฉด? → type
๐๋ ๋ค ์ฌ์ฉ ๊ฐ๋ฅํ์ง๋ง, interface๋ ํ์ฅ์ฑ(extends)์ด ํ์ํ ๋, type์ ๋ ์์ ๋ก์ด ์กฐํฉ์ด ํ์ํ ๋ ์ฌ์ฉ