Interface, Type Alias
ํ์
์คํฌ๋ฆฝํธ์์ ๊ฐ์ฒด์ ์ปค์คํ
ํ์
์ ์ ์ํ๋ ๋ฐฉ๋ฒ์๋ interface
, type
์ด๋ ๊ฒ 2๊ฐ์ง๊ฐ ์๋ค. ์ด 2๊ฐ์ ๋ฐฉ๋ฒ์ ๋ํด์ ์์๋ณด์.
Interface
An interface declaration is another way to name an object type
Typescript ๊ณต์๋ฌธ์์ ์ฐ์ฌ์๋ interface์ ์ค๋ช ์ด๋ค. ํด์ํ์๋ฉด ๊ฐ์ฒด์ ํ์ ์ ๋ณ์นญ์ ์ ํ๋ ๋ค๋ฅธ ๋ฐฉ๋ฒ์ด๋ค.
interface Sample {
name: string;
}
function useInterface(user: Sample){
const {name} = user;
console.log(name);
}
const user1 = '์ธํฐํ์ด์ค'
useInterface(user1); // '์ธํฐํ์ด์ค'
์ด๋ฐ์์ผ๋ก ๊ฐ์ฒด๊ฐ ์ด๋ ํ ํ์ ์ ๊ฐ์ง๊ฒ์ธ์ง ๋ช ์์ ์ผ๋ก ์ ํด์ค์ ์๋ค.
๋ง์ฝ interface๋ก ์ ์ํ ์์ฑ์ ํ์ฅ์ด ํ์ํ๋ค๋ฉด
// extends ํค์๋๋ฅผ ์ฌ์ฉํ ํ์ฅ
interface Sample {
name: string;
}
interface ExtendSample extends Sample {
age : number;
}
const user2 : ExtendSample = {
name : 'extends๋ฅผ ์ฌ์ฉํด ํ์ฅ๋ ์ธํฐํ์ด์ค',
age : 12
}
// ์ ์ธ์ ํ์ฅ
interface ExtendSample {
address : string;
}
const user3 : ExtendSample = {
name : '์ ์ธ์ ํ์ฅ์ ์ฌ์ฉํ ์ธํฐํ์ด์ค',
age : 20,
address : '์์ธ ํน๋ณ์'
}
์ ์์ ์ฝ๋์ฒ๋ผextends
ํค์๋๋ฅผ ์ฌ์ฉํ์ฌ ํ์ฅ ํ๊ฑฐ๋, ๊ฐ์ ์ด๋ฆ์ interface๋ฅผ ๋ค์ ์ ์ธํ์ฌ ํ์ฅํ ์ ์๋ค.
interface๋ ์ ์์์ฒ๋ผ ๊ฐ์ฒด์ ํ์ ์ ์ ์ํ๋๋ฐ ์ฌ์ฉ๋์ง๋ง, ์์ ์๋ฃํ์ ์ฌ์ฉ์ด ๋ถ๊ฐ๋ฅํ๋ค.
// ์๋์ฒ๋ผ ์์ ์๋ฃํ์ interface๋ฅผ ์ ์ํ๋ ๊ฒ์ ๋ถ๊ฐ๋ฅํ๋ค.
interface Address extends string{
}
Type Alias
type alias ์ญ์ interface์ ๋น์ทํ ์ญํ ์ ์ํํ๋ค. ํน์ ํ ํ์
๋๋ interface๋ฅผ ์ฐธ์กฐํ ์ ์๋ ํ์
๋ณ์๋ฅผ ์นญํ๋ ํค์๋์ด๋ค. interface์ ๋ง์ฐฌ๊ฐ์ง๋ก ํ์ฅ์ด ๊ฐ๋ฅํ์ง๋ง extends ํค์๋ ๋์ &
ํค์๋๋ฅผ ์ฌ์ฉํ๋ค.
์ ์ํ ์ ์ interface๋ ์ ์ธ์ ํ์ฅ์ด ๊ฐ๋ฅํ์ง๋ง, type์ ์ ์ธ์ ํ์ฅ์ด ๋ถ๊ฐ๋ฅํ๋ค.
type Sample = {
name : string;
}
const user1 : Sample = {
name : 'ํ์
์ฌ์ฉ'
}
// type ํ์ฅ
type Sample2 = Sample & {
age : number;
}
const user2 : Sample2 = {
name : 'ํ์
ํ์ฅ',
age : 20
}
// Error: Duplicate identifier 'Sample'.
type Sample = {
address : string
}
type์ ์๋ก์ด ์ ํ์ ์ ์ํ๋๊ฒ์ด ์๋๋ผ ๊ธฐ์กด์ ํ์ ์ ๋ํด ์๋ก์ด ๋ณ์นญ์ ์ ์ํ ๋ฟ์ด๋ค.


์ ์ฌ์ง์ ๋ณด๋ฉด interface๋ฅผ ์ฌ์ฉํ๋ฉด ํด๋น ์๋ฃํ์ด ์๋กญ๊ฒ ์์ฑ๋๋๋ฐ ๋ฐํด, type alias๋ฅผ ์ฌ์ฉํ์๋๋ ๋ณ์นญ๋ง ์์ฑ๋ ๊ฒ์ ๋ณผ์ ์๋ค.
๋ฐ๋ผ์, interface์์ ๋ถ๊ฐ๋ฅํ๋ ์์ ์๋ฃํ์ ์ฌ์ฉ์ด ๊ฐ๋ฅํ๋ค.
type PrimitiveType = string;
type PrimitiveType2 = string | number;
์ด๋ฐ์์ผ๋ก ๊ธฐ์กด์ ์ฌ์ฉํ๋ ์์์๋ฃํ์ ๋ํด์ type alias๋ฅผ ์ ์ธ ํ ์๋ ์๋ค.
Last updated