interface
์ธํฐํ์ด์ค๋ ๊ฐ์ฒด๊ฐ ๊ฐ์ ธ์ผ ํ ์์ฑ๊ณผ ๋ฉ์๋๋ฅผ ์ ์ํ๋ ๊ตฌ์กฐ์ ๋๋ค.
๊ฐ์ฒด์ ๊ตฌ์กฐ๋ฅผ ์ ์ํ๊ฑฐ๋, ์์์ ํตํด ์ฝ๋์ ์ฌ์ฌ์ฉ์ฑ์ ๋์ด๋ ๋ฐ ์ฃผ๋ก ์ฌ์ฉํฉ๋๋ค.
type alias
ํน์ ํ์ ์ ์ ์ํ๋ ๋ฐ ์ฌ์ฉ๋ฉ๋๋ค.
๊ฐ์ฒด๋ฅผ ํฌํจํ ๋ค์ํ ํํ์ ํ์ ์ ์ ์ํ๋ ๋ฐ ์ฌ์ฉ๋๋ฉฐ, ๋ ์ ์ฐํ ์ ์๊ฐ ๊ฐ๋ฅํฉ๋๋ค.
๐จ interface๋ '๊ฐ์ฒด์ฉ์ด๋ค.','์์ํ๊ธฐ ์ํ ์ฉ์ด๋ค.'๋ผ๊ณ ๋งํ๋๋ฐ โ ์๋๋ค !! type alias ๋ฐฉ์๋ ๊ฐ์ฒด, ์์ ๋ชจ๋ ๊ฐ๋ฅํ๋ค !!
1๏ธโฃ ์ ์ฐ์ฑ / ์ ๋์จ ํ์ ์ ํผ๋ ๋ฐ์
type alias
type Dog =
| {
eat(): string;
woof(): string;
}
| {};
const jindo: Dog = {
constructor(private name: string) {}
// ์ ๋์จ ํ์
์ ๊ฒฝ์ฐ, ์ด๋ค ์์ฑ์ด ์กด์ฌํ์ง ์์ ์ ์๋ ์ํฉ์ ๊ด๋ฆฌํ๊ธฐ ์ด๋ ค์ธ ์ ์์ต๋๋ค.
eat() {
return `Hello, ${this.name}`;
},
};
Dog ํ์ ์ด ์ ๋์จ ํ์ ์ผ๋ก ์ ์๋์ด ์๊ธฐ ๋๋ฌธ์, jindo ๊ฐ์ฒด๋ ๋น ๊ฐ์ฒด {}์ผ ์๋ ์๊ณ , eat ๋ฐ woof ๋ฉ์๋๋ฅผ ๊ฐ์ง ๊ฐ์ฒด์ผ ์๋ ์์ต๋๋ค.
ํ์ ์คํฌ๋ฆฝํธ๋ ์ด ๊ฒฝ์ฐ, ๋ ๊ฐ์ง ํํ ์ค ํ๋๋ก ์ ์๋๋ฏ๋ก, ๋ชจ๋ ๊ฒฝ์ฐ๋ฅผ ๋ง์กฑํด์ผ ํ๋ค๊ณ ํ๋จํ์ง ์์ต๋๋ค. ์ด๋ ๋ถํ์ํ ํผ๋์ ์ผ๊ธฐํ ์ ์์ต๋๋ค.
interface
// Dog ์ธํฐํ์ด์ค๋ eat๊ณผ woof๋ผ๋ ๋ฉ์๋๊ฐ ํ์์์ ๋ถ๋ช
ํ ๋ํ๋
๋๋ค
interface Dog {
eat(): string;
woof(): string;
}
class Jindo implements Dog {
constructor(private name: string) {}
eat() {
return `Hello, ${this.name}`;
}
woof() {
return 'Woof!';
}
}
2๏ธโฃ ํ์ฅ, ๋ณํฉ
interface
interface Student {
name: string;
}
interface Student {
createdAt: Date;
}
// ๋ Student ์ธํฐํ์ด์ค๋ ํ๋๋ก ๋ณํฉ
const student: Student = {
name: 'Alice',
createdAt: new Date(),
};
type alias
type alias๋ ๊ฐ์ ์ด๋ฆ์ผ๋ก ์ฌ์ ์ํ ์ ์์ผ๋ฉฐ, ์ฌ๋ฌ ํ์ ์ ํฉ์น๋ ๋ฐฉ์์ผ๋ก ์๋ก์ด ํ์ ์ ๋ง๋ค์ด์ผ ํฉ๋๋ค.
interface๋ ์ง์ ์ ์ผ๋ก ๋ค๋ฅธ ์ธํฐํ์ด์ค๋ฅผ ํ์ฅํ ์ ์๊ณ , ๋์ผํ ์ด๋ฆ์ผ๋ก ์ฌ๋ฌ ๋ฒ ์ ์ธํ ์ ์์ด ํฉ์น๋ ๋ฐฉ์์ผ๋ก ๊ธฐ๋ฅ์ ์ถ๊ฐํ ์ ์์ต๋๋ค.
3๏ธโฃ ๊ธฐ๋ฅ
- type alias๋ ๊ธฐ๋ณธ ํ์ , ์ ๋์จ ํ์ , ํํ ๋ฑ ๋ค์ํ ํ์ ์ ์์ ์ฌ์ฉํ ์ ์์ต๋๋ค.
- interface๋ ์ฃผ๋ก ๊ฐ์ฒด์ ๊ตฌ์กฐ๋ฅผ ์ ์ํ๋ ๋ฐ ์ฌ์ฉ๋๋ฉฐ, ํด๋์ค์ ํจ๊ป ์ ์๋ํฉ๋๋ค.
์์ฝ
์ผ๋ฐ์ ์ผ๋ก ๊ฐ์ฒด ๊ตฌ์กฐ๋ฅผ ์ ์ํ๊ณ ํ์ฅ์ฑ์ด ํ์ํ ๊ฒฝ์ฐ์๋ interface๋ฅผ ์ฌ์ฉํฉ๋๋ค. interface๋ ํ์ฅ์ด ์ฉ์ดํ๊ณ ๊ฐ์ ์ด๋ฆ์ผ๋ก ๋ณํฉ์ด ๊ฐ๋ฅํ๊ธฐ ๋๋ฌธ
๋ฐ๋ฉด, ์ ๋์จ ํ์ ์ด๋ ๋งคํ๋ ํ์ , ํจ์ ํ์ ๊ณผ ๊ฐ์ด ๋ณต์กํ ํ์ ์กฐํฉ์ด ํ์ํ ๋๋ type์ ์ฌ์ฉํฉ๋๋ค. type์ ๋ ์ ์ฐํ๊ณ ๋ค์ํ ํ์ ํํ์ด ๊ฐ๋ฅ
์ฝ๊ฒ ๋๋ฌผ์ ํ์ ์ผ๋ก ๋ง๋ค์ด ๋ณด๋ฉด, interface๋ ๋๋ฌผ์ ๊ธฐ๋ณธ ๊ตฌ์กฐ(์ด๋ฆ, ๋์ด ๋ฑ)๋ฅผ ์ ์ํ ๋ ์ฌ์ฉํ๊ณ , type์ ๋๋ฌผ์ด ์ด ์ ์๋ ์ฅ์(land ๋๋ water) ๊ฐ์ ์ ๋์จ ํ์ ์ ์ ์ํ ๋ ์ฌ์ฉํฉ๋๋ค. ์๋ฅผ ๋ค์ด, interface๋ '๋๋ฌผ' ๊ฐ์ฒด๋ฅผ ์ ์ํ๊ณ , type์ '์ก์ง ๋๋ฌผ'๊ณผ 'ํด์ ๋๋ฌผ'์ ๊ฒฐํฉํ๋ ๋ฐ ์ ํฉํฉ๋๋ค.
'๐ก ์์๋๋ฉด ์ข์ ๊ฒ๋ค > ๋ฉด์ ๋๋น' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[ํ๋ก ํธ์๋ ๋ฉด์ ์ง๋ฌธ] - ๋ธ๋ผ์ฐ์ ๋ ์ด๋ป๊ฒ ๋์ํ๋๊ฐ (0) | 2024.10.10 |
---|---|
[Javascript] - this์ ์๋ฏธ (0) | 2024.10.04 |