Frontend ๊ฐœ๋ฐœ์ž - hyo.loui

ํƒ€์ž…์Šคํฌ๋ฆฝํŠธ - interface extension(์ธํ„ฐํŽ˜์ด์Šค ํ™•์žฅ) ๋ณธ๋ฌธ

Typescript

ํƒ€์ž…์Šคํฌ๋ฆฝํŠธ - interface extension(์ธํ„ฐํŽ˜์ด์Šค ํ™•์žฅ)

hyo.loui 2023. 1. 19. 16:10

 

๐ŸŽฏ๋ชฉ์  :

TS  Interface extension(์ธํ„ฐํŽ˜์ด์Šค ํ™•์žฅ), ์ •๋ฆฌ ๋ฐ ๋ณต์Šต

 


1. ์ธํ„ฐํŽ˜์ด์Šค ํ™•์žฅ

ํƒ€์ž… ๋ณ„์นญ๊ณผ ์ธํ„ฐํŽ˜์ด์Šค์˜  ์ฐจ์ด์ ์€ ํƒ€์ž…์˜ ํ™•์žฅ ๊ฐ€๋Šฅ ์—ฌ๋ถ€์ด๋‹ค.

์ธํ„ฐํŽ˜์ด์Šค๋Š” ํ™•์žฅ์ด ๊ฐ€๋Šฅํ•œ๋ฐ ํƒ€์ž… ๋ณ„์นญ์€ ํ™•์žฅ์ด ๋ถˆ๊ฐ€๋Šฅํ•˜๋‹ค.

์ด ๋•Œ๋ฌธ์—, type ๋ณด๋‹ค๋Š” interface๋กœ ์„ ์–ธํ•ด์„œ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์„ ์ถ”์ฒœํ•œ๋‹ค.

 

 

๋ฐฉ๋ฒ•์€ ๋‘๊ฐ€์ง€ ์ด๋‹ค

 

1. extends

 

interface ์ƒˆ๋กœ์šด ์ธํ„ฐํŽ˜์ด์Šค๋ช… + extends + ๋ถ™์ผ ์ธํ„ฐํŽ˜์ด์Šค๋ช… 

// interface extenstion

interface Person {
  name: string;
  age: number;
}
interface Korea extends Person {
  birth: "korea";
}
//          vv ์•„๋ž˜ ๋‚ด์šฉ๊ณผ ๋™์ผํ•˜๋‹ค
interface Korean {
  name: string;
  age: number;
  birth: "korea";
}

 

2. ์„ ์–ธ์  ํ™•์žฅ

 

interface ์ธํ„ฐํŽ˜์ด์Šค๋ช…์„ ์žฌ์„ ์–ธ ํ•˜๋Š” ๊ฒƒ

interface teset {
  title: string;
}

interface teset {
  ts: number;
}

// ๊ฐ™์€ interface ๋ช…์œผ๋กœ teset๋ฅผ ๋‹ค์‹œ ๋งŒ๋“ ๋‹ค๋ฉด, ์ž๋™์œผ๋กœ ํ™•์žฅ์ด ๋œ๋‹ค.

const text: teset = {
  title: "header",
  ts: 12,
};

console.log("๐Ÿ‘‰๐Ÿ‘‰  text", text); // ๐Ÿ‘‰๐Ÿ‘‰  text { title: 'header', ts: 12 }

2.  ์ธํ„ฐํŽ˜์ด์Šค ํ™•์žฅ ํ™œ์šฉ ํ•˜๊ธฐ

 

interface Korean {
  name: string;
  age: number;
  birth: "korea";
}
interface Developer {
  job: "developer";
}
interface KorandDev extends Korean, Developer {
  // ํƒ€์ž…์„ ์„ ์–ธํ•˜์ง€ ์•Š์•„๋„ ์•„๋ž˜์ฒ˜๋Ÿผ ๋“ค์–ด์˜ค๊ฒŒ ๋œ๋‹ค
  // name: string;
  // age: number;
  // birth: "korea";
  // job: "developer";
}
const test0: KorandDev = {
  name: "์Šนํšจ",
  age: 27,
  birth: "korea",
  job: "developer",
};
console.log("๐Ÿ‘‰๐Ÿ‘‰  test0", test0); 
//๐Ÿ‘‰๐Ÿ‘‰  test0 { name: '์Šนํšจ', age: 27, birth: 'korea', job: 'developer' }

 


3. intersection Type: ์—ฌ๋Ÿฌ ํƒ€์ž…์„ ๋ชจ๋‘ ๋งŒ์กฑํ•˜๋Š” ํ•˜๋‚˜์˜ ํƒ€์ž…

 

// intersection type
interface Person {
  name: string;
  age: number;
}

interface Develop {
  name: string;
  skill: string;
}

type Devjob = Person & Develop;

const abcPerson: Devjob = {
  name: "john",
  age: 12,
  skill: "html",
};
console.log("๐Ÿ‘‰๐Ÿ‘‰  abcPerson", abcPerson);

 

 


 

 ์ตœ์ข… ์ •๋ฆฌ 

  1. ํƒ€์ž…๋ณ„์นญ๊ณผ ์ธํ„ฐํŽ˜์ด์Šค์˜ ๊ฐ€์žฅํฐ ์ฐจ์ด์ ์€ ํ™•์žฅ ๊ฐ€๋Šฅ ์—ฌ๋ถ€์ด๋‹ค.
  2. type ๋ณด๋‹ค๋Š” interface๋กœ ์„ ์–ธํ•ด์„œ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์„ ์ถ”์ฒœ.
  3. ํ™•์žฅ ๋ฐฉ๋ฒ•์€ [ extends ํ™œ์šฉ, ์„ ์–ธ์  ํ™•์žฅ ] 2๊ฐ€์ง€๋กœ ๋ถ„๋ฅ˜๋œ๋‹ค.
  4. intersection Type ์„ ์‚ฌ์šฉํ•  ๋•Œ ์ค‘๋ณต๋˜๋Š” ์†์„ฑ์ด ์žˆ์–ด๋„ ๋œ๋‹ค.