[TypeScript] 02 - Types

Young-masonΒ·2021λ…„ 2μ›” 13일
0
post-thumbnail

🌟 νƒ€μž…μŠ€ν¬λ¦½νŠΈλ₯Ό ν•™μŠ΅ν•˜λ©΄μ„œ 배운 λ‚΄μš©λ“€μ„ λΈ”λ‘œκ·Έμ— κΈ°λ‘ν•©λ‹ˆλ‹€ (feat. λ“œλ¦Όμ½”λ”©)

✐ νƒ€μž…μ΄λž€? (νƒ€μž…μ˜ 원칙)

  • λ³€μˆ˜λŠ” 데이터λ₯Ό 담을 μƒμžμ™€ κ°™λ‹€. νƒ€μž…μ„ μ§€μ •ν•΄μ€€λ‹€λŠ” 것은 이 μƒμžμ— 라벨을 λΆ™μ—¬μ„œ μ•ˆμ— λ“€μ–΄κ°€μ•Όν•  λ‚΄μš©λ¬Όμ„ λͺ…μ‹œν•˜λŠ” 것이라고 이해할 수 μžˆλ‹€.
  • λ³€μˆ˜ 뿐만 μ•„λ‹ˆλΌ 객체의 킀와 κ°’, ν•¨μˆ˜μ˜ Input, ouputμ—μ„œλ„ νƒ€μž…μ„ λͺ…μ‹œν•΄μ£ΌλŠ” 것이 μ’‹λ‹€
  • μ΅œλŒ€ν•œ νƒ€μž…μ΄ 보μž₯λ˜λŠ” λ°©μ‹μœΌλ‘œ μ„ νƒν•΄μ„œ ν”„λ‘œκ·Έλž˜λ° ν•˜λŠ”κ²ƒμ΄ μ€‘μš”ν•˜λ‹€!

✐ Basic Types

  • number | string | boolean
const num: number = -6;  // number

const str: string = 'hello';  // string

const boal: boolean = false;  // boolean
  • undefined | null | unkwown | any
/* undefined */ 

let name: undefined; // πŸ’© μ΄λŸ°μ‹μœΌλ‘  잘 쓰이지 μ•ŠμŒ

let age: number | undefined // numberνƒ€μž… ν˜Ήμ€ undefined
age = undefined;
age = 1;  

/* null */

let person: null; // πŸ’©
let person: string | null;

/* unknown : πŸ’© λͺ¨λ“  νƒ€μž…μ΄ ν—ˆμš©λ˜λ―€λ‘œ 잘 쓰이지 μ•ŠμŒ */

let notSure: unknown = 0;
notSure = 'he';
notSure = true;

/* any : πŸ’© λͺ¨λ“  νƒ€μž…μ΄ ν—ˆμš©λ˜λ―€λ‘œ 잘 쓰이지 μ•ŠμŒ */

let anything: any = 0;
anything = 'hello';
  • void | never | object
/* void : 아무것도 λ¦¬ν„΄ν•˜μ§€ μ•ŠλŠ” ν•¨μˆ˜μ˜ νƒ€μž… (μƒλž΅ κ°€λŠ₯) */

function print(): void {
  console.log('hello');
  return;
}

let unusable: void = undefined; // πŸ’©

/* never : μ ˆλŒ€ λ¦¬ν„΄λ˜μ§€ μ•ŠλŠ” ν•¨μˆ˜μ— λŒ€ν•΄ λͺ…μ‹œν•˜κΈ° μœ„ν•΄ μ“°μž„ (μ—λŸ¬, λ¬΄ν•œλ£¨ν”„ λ“±)  */

function throwError(message: string): never {
  throw new Error(message);
  // while (true) {}
}

/* object : function, array λͺ¨λ‘ object에 ν¬ν•¨λ˜λ―€λ‘œ 보닀 더 μ •ν™•ν•˜κ²Œ λͺ…μ‹œν•΄μ•Όν•¨ */ 

let obj: object; //πŸ’©
function acceptSomeObject(obj: object) {}
acceptSomeObject({ name : 'Mason' })

✐ Function

  • Basic
function add(num1: number, num2: number): number {
  return num1 + num2;
}

/* Promise λ¦¬ν„΄ν•˜λŠ” 경우 */
function fetchNum(id: string): Promise<number> {
  // fetch code...
  return new Promise((resolve, reject) => {
    resolve(100);
  });
}
  • 인자λ₯Ό μ˜΅μ…”λ„ν•˜κ²Œ λ°›λŠ” 경우 ( Optional Parameter )
function printName(firstName: string, lastName?: string) {
  console.log(firstName);
  console.log(lastName);
}

printName('Steve', 'Jobs');  // 'Steve', 'Jobs'
printName('Mason'); // 'Mason', 'undefined'
  • μΈμžμ— λ””ν΄νŠΈ 값을 μΆ”κ°€ν•˜λŠ” 경우 ( Default Parameter )
function printMessage(message: string = 'default message') {
  console.log(message);
}

printMessage(); // 'default message'
  • 인자 κ°œμˆ˜κ°€ μ •ν•΄μ Έ μžˆμ§€ μ•Šμ€ 경우 ( Rest Parameter )
function addNumbers(...numbers: number[]): number {
  return numbers.reduce((a, b) => a + b);
}

addNumbers(1, 2); // 3
addNumbers(1, 2, 3, 4, 5); // 15

✐ Array

  • array
// 첫 번째 방법 - elementType[]
const fruits: string[] = ['apple', 'banana'];

// 두 번째 방법 - Array<elementType>
const scores: Array<number> = [1, 3, 4];

// immutable λ°°μ—΄ 인자둜 λ°›κΈ°
function printArray(fruits: readonly string[]) {}
  • tuple
let student: [string, number];
student = ['name', 123];
student = [123, 'name']; // Error!
student[0]; // name;
student[1]; // 123

const [name, age] = student;

// Tuple은 인덱슀둜 μ ‘κ·Όν•΄μ•Ό ν•˜λ―€λ‘œ 가독성이 λ–¨μ–΄μ§€λŠ” 편..
// 주둜 interface, type alias, class λ°©μ‹μœΌλ‘œ λŒ€μ²΄ν•˜μ—¬ μ‚¬μš©

✐ Type Alias

  • μ»€μŠ€ν…€ νƒ€μž… λ§Œλ“€κΈ° ( Type Alias )
type Text = string; // Text λΌλŠ” νƒ€μž…μ„ 생성
const name: Text = 'Mason' // name λ³€μˆ˜μ— Text νƒ€μž… 적용

// 객체에 type alias μ μš©ν•˜κΈ°
type Student = {
  name: string,
  age: number
}

const me: Student {
  name: 'Mason',
  age: 29
}
  • κ°’ 자체λ₯Ό νƒ€μž…μœΌλ‘œ κ²°μ •ν•  수 있음 ( String Literal Types )

type JSON = 'json';
const json: JSON = 'json';
const json: JSON = 'others' // Error!

✐ Union

  • μ—¬λŸ¬ 값을 νƒ€μž…μœΌλ‘œ 지정 ν•  수 있음 ( Union Types )

    ν™œμš©λ„κ°€ λ†’λ‹€ πŸ‘

type Direction = 'left' | 'right' | 'up' | 'down';
function move(direction: Direction) {
  console.log(direction);
}
move('down');

type TileSize = 8 | 16 | 32;
const tile: TileSize = 16;
  • μ‹€μ „ 둜그인 예제
// Discriminated Union
// λ™μΌν•œ ν‚€(result), λ‹€λ₯Έ 값을 κ°€μ§€κ²Œ 함 
// -> printLoginState ν•¨μˆ˜ λ‚΄μ—μ„œ state.result 에 μ ‘κ·Όν•  수 있음

type SuccessState = {
  result:'success';
  response: string;
}
type failState = {
  result: 'fail';
  reason: string;
}
type LoginState = SuccessState | FailState;

function login(): LoginState {
  return {
    result: 'success',
    response: {
      body: 'logged in!'
    }
  };
}

function <printLoginState(state: LoginState) {
  if(state.result) {
    console.log(`πŸŽ‰ ${state.response.body}`);
  } else {
    console.log(`😭 ${state.reason}`)
  }
}

✐ Intersection Types

  • λ‹€μ–‘ν•œ νƒ€μž…λ“€μ„ λ¬Άμ–΄μ„œ μ„ μ–Έν•  수 있음
type Student = {
  name: string;
  score: number;
}

type Worker = {
  employeeId: number;
  work: () => void;
}

function internWork(person: Student & Worker) {
  console.log(person.name, person.employeeId, person.work());
}

internWork({
  name: 'mason',
  score: 1,
  employeeId: 123,
  work: () => {}
})

✐ Enum

  • μ—¬λŸ¬κ°€μ§€ μƒμˆ˜ 값듀을 ν•œ 곳에 λͺ¨μ•„μ„œ μ •μ˜ν•  수 μžˆλ„λ‘ λ„μ™€μ£ΌλŠ” νƒ€μž…
// JavaScript
const MAX_NUM = 6;
const MAX_STUDENTS_PER_CLASS = 10;
const DAYS_ENUM = Object.freeze({"MONDAY": 0, "TUESDAY": 1, "WEDNESDAY": 2});
const dayOfToday = DAYS_ENUM.MONDAY;

// TypeScript
enum Days {
  Monday, // enum에 값을 ν• λ‹Ή ν•  수 μžˆλ‹€. ex) Monday = 'mon'
  Tuesday,
  Wednesday,
}

// 값이 ν• λ‹Ή λ˜μ§€ μ•ŠμœΌλ©΄ 0λΆ€ν„° μ°¨λ‘€λŒ€λ‘œ ν• λ‹Ήλœλ‹€
let day = Days.Monday
console.log(day) // -> 0 .. 

// enum에 값이 ν• λ‹Ήλœ λ’€ λ‹€λ₯Έ 값을 ν• λ‹Ήν•  수 μžˆλ‹€ (νƒ€μž…μ΄ μ •ν™•ν•˜κ²Œ 보μž₯λ˜μ§€ μ•ŠμŒ)
day = 10

// λ”°λΌμ„œ νƒ€μž…μŠ€ν¬λ¦½νŠΈμ—μ„œ enum을 가급적 쓰지 μ•ŠλŠ” 것이 μ’‹μœΌλ©° Union νƒ€μž…μœΌλ‘œ λŒ€μ²΄ κ°€λŠ₯ν•˜λ‹€
type dayOfWeek = 'Monday' | 'Tuesday' | 'Wednesday'

✐ Inference

  • νƒ€μž… μΆ”λ‘  ( Type Inference )
let text = 'hello';
text = 1 // Error!

// μΈμžμ— νƒ€μž…μ„ λͺ…μ‹œν•˜μ§€ μ•ŠμœΌλ©΄ any둜 μΆ”λ‘ 
function print(message = 'hello') {
  console.log(message);
}
print('hello');
print(1);

function add(x: number, y: number) {
	return x + y;
}
// 리턴 νƒ€μž…μ„ λͺ…μ‹œν•˜μ§€ μ•Šμ•„λ„ number둜 μΆ”λ‘ 
const result = add(1, 2) // type: number

κ·Έλž˜λ„ νƒ€μž…μ€ μ •ν™•ν•˜κ²Œ λͺ…μ‹œν•΄ μ£ΌλŠ”κ²Œ μ’‹λ‹€ 😭

✐ Type Assertion

  • 정말 μžˆλ‹€κ³  μž₯λ‹΄ν•  수 μžˆμ„ λ•Œ μ‚¬μš©ν•˜κΈ° ( ! )
function jsStrFunc(): any {
    return 2;
  }
  const result = jsStrFunc();
  console.log((result as string).length);
  console.log((<string>result).length);

  const wrong: any = 5;
  console.log((wrong as Array<number>).push(1)); // 😱

  function findNumbers(): number[] | undefined {
    return undefined;
  }
  const numbers = findNumbers()!;
  numbers.push(2); // 😱

  const button = document.querySelector('class')!;
profile
Frontend Developer

0개의 λŒ“κΈ€