๐Ÿ‘ฉ‍๐Ÿ’ป/TypeScript

[TypeScript] ์ ์žฌ์ ์†Œ์— interface์™€ type์„ ์“ฐ๋Š” ๋ฐฉ๋ฒ•๊ณผ ์Šคํƒ€์ผ ๊ฐ€์ด๋“œ

ํ•œ๋‚˜ 2022. 1. 27. 22:15

๋ช‡ ๊ฐœ์˜ ํ”„๋กœ์ ํŠธ์—์„œ ํƒ€์ž…์Šคํฌ๋ฆฝํŠธ๋ฅผ ์“ฐ๊ณ  ๋‚˜์„œ๋ถ€ํ„ฐ๋Š” ์ด์ œ ํƒ€์ž…์Šคํฌ๋ฆฝํŠธ ์ด์ „์œผ๋กœ ๋Œ์•„๊ฐ€์ง€ ๋ชปํ•˜๊ณ  ์žˆ๋‹ค. ๊ทธ๋Ÿฐ๋ฐ ๋˜ ์ฒด๊ณ„์ ์œผ๋กœ ํƒ€์ž…์Šคํฌ๋ฆฝํŠธ๋ฅผ ์จ์˜จ ๊ฒŒ ์•„๋‹ˆ๋ผ, ์“ฐ๋Š” ํƒ€์ž…๋งŒ ์“ฐ๊ณ , ๊ทธ๋•Œ ๊ทธ๋•Œ ์—๋Ÿฌ๋ฅผ ํ•ด๊ฒฐํ•ด ๋‚˜๊ฐ€๋ฉด์„œ ์ฒด๋“ํ•œ ๊ฒƒ์ธ์ง€๋ผ ์‹œ๊ฐ„์ด ๋‚˜๋ฉด ์ž˜ ์ •๋ฆฌ๋œ ๋ฌธ์„œ๋“ค์„ ์ฝ์œผ๋ฉด์„œ, ๋ฌธ๋ฒ•์„ ์ตํžˆ๋ ค๊ณ  ํ•œ๋‹ค.

React Native๋ฅผ ํ•  ๋•Œ ๊ฐ€์žฅ TS๋ฅผ ๋งŽ์ด ์ผ๋Š”๋ฐ, ์ด๋•Œ๋Š” ๊ฑฐ์˜ interface๋กœ ์ ์ฒ ํ•˜๋‹ค์‹œํ”ผํ–ˆ๋‹ค. type๊ณผ interface๊ฐ€ ๊ฑฐ์˜ ๋น„์Šทํ•˜๋‹ค๋Š” ๊ฒƒ์€ ์•Œ๊ณ  ์žˆ์—ˆ์ง€๋งŒ, ๋”ฑ ๊ฑฐ๊ธฐ๊นŒ์ง€์–ด์„œ ์ด๋ฒˆ ๊ธฐํšŒ์— ์ •๋ฆฌํ•ด๋ดค๋‹ค.

Interface

interface๋Š” object ํƒ€์ž…์„ ์ •์˜ํ•˜๋Š” ๋‹ค๋ฅธ ๋ฐฉ๋ฒ•์ด๋‹ค. ์ด๋ฆ„๊ณผ ๋‚˜์ด๋ฅผ ๋ฐ›๋Š” user๋ผ๋Š” ์ด๋ฆ„์˜ ๊ฐ์ฒด ์ •๋ณด๊ฐ€ ์žˆ์„ ๋•Œ ์•„๋ž˜์ฒ˜๋Ÿผ interface๋ฅผ ์„ ์–ธํ•  ์ˆ˜ ์žˆ๋‹ค.

interface User {
    name: string;
      age: number;
}

๋งŒ์ผ, interface์˜ ์žฌ์‚ฌ์šฉ์„ฑ์„ ๋†’์ด๊ธฐ ์œ„ํ•ด ํ™•์žฅ์„ ํ•˜๊ณ ์ž ํ•œ๋‹ค๋ฉด ์–ด๋–ป๊ฒŒ ์จ์•ผ ํ• ๊นŒ? ์•ž์„œ ์‚ดํŽด๋ณธ ๊ธฐ๋ณธ user ํ˜•ํƒœ๋ฅผ ์ด์ œ ํ•™์ƒ์˜ property๋ฅผ ์ถ”๊ฐ€ํ•ด 'ํ•™์ƒ'์ด๋ผ๋Š” interface๋ฅผ ๋งŒ๋“ค์–ด๋ณด์ž.

interface User {
    name: string;
      age: number;
}

interface Student extends User {
    major: string;
}

Type ๋˜๋Š” Type Aliases

type๋„ ๋งˆ์ฐฌ๊ฐ€์ง€๋กœ ์•„๋ž˜์ฒ˜๋Ÿผ ์ฝ”๋“œ๋ฅผ ์“ด๋‹ค. ๋งค์šฐ ์œ ์‚ฌํ•œ ๊ฒƒ์„ ์•Œ ์ˆ˜ ์žˆ๋‹ค.

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

๊ทธ๋Ÿผ ์ด type์„ ๋˜ ํ™•์žฅํ•ด์„œ ์“ฐ๊ณ ์ž ํ•œ๋‹ค๋ฉด ์–ด๋–จ๊นŒ?

type Student = User & {
    major: string;
}

์ด๋Ÿฐ ์‹์œผ๋กœ & ์—ฐ์‚ฐ์ž๋ฅผ ํ†ตํ•ด ํƒ€์ž…์„ ํ™•์žฅํ•ด์„œ ์“ด๋‹ค.

interface์™€ type์˜ ์ฐจ์ด์ 

์œ„์— ๋‹ค๋ฃฌ ๊ฒƒ์ฒ˜๋Ÿผ ๋‘˜์˜ ๊ฐ€์žฅ ํฐ ์ฐจ์ด์ ์€ ์ถ”๊ฐ€ํ•˜๊ณ  ์‹ถ์€ property๊ฐ€ ์žˆ์„ ๋•Œ ์–ด๋–ป๊ฒŒ ์ถ”๊ฐ€ํ•˜๋Š”์ง€์— ๋Œ€ํ•œ ๋ฐฉ์‹์— ์žˆ๋‹ค. ๊ทธ๋ž˜์„œ ์—ฌ๋Ÿฌ ๋ฌธ์„œ์—์„œ๋Š” ๋Œ€์ฒด๋กœ ํ™•์žฅ ๊ฐ€๋Šฅ์„ฑ์ด ์žˆ๋Š” interface๋ฅผ ์“ฐ๋‹ค๊ฐ€, type์ด ํ•„์š”ํ•  ๋•Œ ์ด๋ฅผ ๋„์ž…ํ•˜๋Š” ๊ฒƒ์„ ์ถ”์ฒœํ•œ๋‹ค.

Style Guide

์ฐธ๊ณ ๋กœ type๊ณผ interface ๋ชจ๋‘ UpperCamelCase๋ฅผ ๊ถŒ๊ณ ํ•œ๋‹ค.

TS Style Guide

 

์ถœ์ฒ˜

 

 

TS Style Guide

// Event handlers may be anonymous functions or arrow function properties. class Component { onAttached() { // The event is emitted by this class, no need to uninstall. this.addEventListener("click", () => { this.listener(); }); // this.listener is a stabl

ts.dev

https://www.typescriptlang.org/docs/handbook/2/everyday-types.html

 

Documentation - Everyday Types

The language primitives.

www.typescriptlang.org