์“ฐ์œฝํ„ฐ๋””/TypeScript

ํƒ€์ž…์Šคํฌ๋ฆฝํŠธ_๋…ผ๋ฆฌ์—ฐ์‚ฐ์žํ™œ์šฉ

Kkan 2023. 2. 11. 23:32
728x90
๋ฐ˜์‘ํ˜•

๐ŸŽˆ์ฃผ์ œ: ๋…ผ๋ฆฌ ์—ฐ์‚ฐ์ž ํ™œ์šฉ ํƒ€์ž…

 

1. ํƒ€์ž… ๋ณ„์นญ (Type Aliases)

  • ์˜๋ฏธ์—†๋Š” ๋ฐ˜๋ณต์„ ์ค„์ด๊ณ  ํƒ€์ž…์„ ๋ช…์‹œ์ ์œผ๋กœ ์‚ฌ์šฉํ•˜๋„๋ก ๋•๋Š”๋‹ค.
  • let, const๋ฅผ ์„ ์–ธํ•ด ๋ณ€์ˆ˜๋ฅผ ์ดˆ๊ธฐํ™” ํ•˜๋“ฏ์ด ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.
  • ์ปดํŒŒ์ผ๋Ÿฌ๊ฐ€ ๋”ฐ๋กœ ์ถ”๋ก ํ•˜์ง€ ์•Š๋Š”๋‹ค.
// ํƒ€์ž… ๋ณ„์นญ ์„ค์ •
type str = string;
type num = number;
type numArr = num[];
type strArr = string[];

// ๋ณ„์นญ ์‚ฌ์šฉ!
type Person = {
    name: str;
    age: num;
    family: strArr;
}

interface๋Š” type aliases์™€ ๋‹ค๋ฅด๊ฒŒ ํ•  ์ค„ ์•„๋Š” ๊ฒƒ์ด ๋งŽ๋‹ค! (์ถ”๋ก ๋„ ๊ณ„์† ํ•˜๊ณ , ๊ตฌ์กฐํ™” ํ•˜๊ธฐ์— ์ข‹์Œ.)

MS์—์„œ๋Š” ์ด๋Ÿฐ  type aliases ๋ฅผ ์œ„ํ•ด ์—ฌ๋Ÿฌ๊ฐ€์ง€ ๊ธฐ๋Šฅ๋“ค์„ ์ถ”๊ฐ€ ์ค‘์— ์žˆ๋‹ค๊ณ  ํ•œ๋‹ค.

 

1-1. ์œ ๋‹ˆ์–ธ ํƒ€์ž…

 

์ง„์งœ ๋งŽ์ด ์‚ฌ์šฉํ•˜๋Š” ํƒ€์ž…์ด๋‹ค.

์•„๊นŒ๋„ ๊ณ„์† ์ผ์„ ์ •๋„๋‹ค..ใ„ทใ„ท

ํ•ฉ์ง‘ํ•ฉ์ด๋ผ๊ณ  ์ƒ๊ฐํ•˜๋ฉด ๋œ๋‹ค. 

type StringNumber = string | number;

const str: StringNumber = 'STR';
const num:StringNumber = 123;

 

์ด๋ ‡๊ฒŒ๋„ ์‚ฌ์šฉ ๊ฐ€๋Šฅ!

type Gender = 'M' | 'F';

 

1-2. ๊ต์ฐจ ํƒ€์ž…(Intersection)

 

๊ต์ฐจํƒ€์ž…์€ ๊ต์ง‘ํ•ฉ์ด๋‹ค.

์—ฐ๊ฒฐ๋œ ํƒ€์ž… ๋ชจ๋‘ ๋งŒ์กฑํ•ด์•ผํ•œ๋‹ค๋Š” ๋œป!

ํ•˜์ง€๋งŒ, ์ž˜ ์“ฐ์ด์ง€๋Š” ์•Š๋Š”๋‹ค.

 

type StringNumber = string & number;

const str: StringNumber = 'STR';
// Error: Type 'string' is not assignable to type 'never'.

const num:StringNumber = 123;
// Error: Type 'number' is not assignable to type 'never'.

์˜ค๋ฅ˜๊ฐ€ ๋‚œ๋‹ค. string ํƒ€์ž…์ด๋ฉด์„œ number ํƒ€์ž… ์กฐ๊ฑด์— ๋งž์ง€ ์•Š๊ธฐ ๋•Œ๋ฌธ์—..

 

type Person = {
    name: string;
    age: number;
}

type Student = {
    name: string;
    id: number;
}

const person1: Person & Student = {
    name: 'kkan',
    age: 22,
    id: 123123
}

์ด๋ ‡๊ฒŒ Person๊ณผ Student  ๋ชจ๋‘ ๋งŒ์กฑํ•ด์•ผ OK!

 

1-3. ์œ ๋‹ˆ์–ธ ํƒ€์ž… ํŒ๋ณ„

 

์ถ”๋ก ํ•˜๊ธฐ ์–ด๋ ค์šด ์œ ๋‹ˆ์˜จ ํƒ€์ž…์„ ์ถ”๋ก ํ•˜๊ธฐ ์œ„ํ•จ์ด๋‹ค.

 

interface Male {
    name: string;
    age: number;
    gender: 'M'
}

interface Female {
    name: string;
    age: number;
    gender: 'F'
}

// ๋ˆ„๊ตฐ๊ฐ€ ํ•ฉ์ณ๋†“์€ ์œ ๋‹ˆ์˜จ ํƒ€์ž…..
type Person = Male | Female;

function createPerson({name, age, gender}: Person) {
    return {
        name, age, gender
    };
}

function createMale({name, age, gender}: Person): Male {
    return {
        name, age, gender
    };
}

// Error: Type '"M" | "F"' is not assignable to type '"M"'.
// Type '"F"' is not assignable to type '"M"'.

 

ํ˜„์žฌ ์ฝ”๋“œ๋ฅผ ์‚ดํŽด๋ณด๋ฉด ์œ ๋‹ˆ์˜จ ํƒ€์ž…์œผ๋กœ ์ธํ•ด ์ถ”๊ฐ€์ ์ธ ์ž‘์—…์„ ๋” ํ•ด์•ผํ•˜๋Š” ์ƒํ™ฉ์ด๋‹ค.

๋•Œ๋ฌธ์— ๋ฌด๋ถ„๋ณ„ํ•œ ์œ ๋‹ˆ์˜จ ํƒ€์ž… ์‚ฌ์šฉ์œผ๋กœ ์ธํ•ด (ํ˜น์€ ๋ถˆํ•„์š”ํ•œ ํƒ€์ž… ์‚ฌ์šฉ) ๋ถˆํŽธํ•œ ์ž‘์—…๋“ค์„ ๋” ํ•˜์ง€ ์•Š๋„๋ก ํ•œ๋‹ค.

 

End.

728x90
๋ฐ˜์‘ํ˜•