04장 함수와 메서드

Iris·2022년 1월 3일
0
post-thumbnail

📖 전예홍, ⌈Do it! 타입스크립트 프로그래밍⌋, 이지스퍼블리싱, 2021

04-4 일등 함수 살펴보기

콜백 함수

export const init = (callback: () => void): void => {
  console.log('default initialization finished.')
  callback()
  console.log('all initialization finished.')
}
import {init} from './init'

init(() => console.log('custom initialization finished.'))

// 실행 결과
// default initialization finished.
// custom initialization finished.
// all initialization finished.

고차 함수와 클로저, 그리고 부분 함수

export type NumbrToNumberFunc = (number) => number

export const add = (a: number): NumberToNumberFunc => {
  const _add: NumberToNumberFunc = (b: number): number => {
    return a + b // 클로저
  }
  return _add
}
import {NumberToNumberFunc, add} from './add'

let fn: NumberToNumberFunc = add(1)
let result = fn(2)

console.log(result) // 3
console.log(add(1)(2)) // 3

04-5 함수 구현 기법

객체 생성 시 값 부분을 생략할 수 있는 타입스크립트 구문

export type Person = {name: string, age: number}
export const makePerson = (name: string, age: number = 10): Person => {
  const person = {name, age}
  return person
}

console.log(makePerson('Iris')) // { name: 'Iris', age: 10 }
console.log(makePerson('Iris', 24)) // { name: 'Iris', age: 24 }

객체를 반환하는 화살표 함수 만들기

export type Person = {name: string, age: number}
export const makePerson = (name: string, age: number = 10): Person => ({name, age})

console.log(makePerson('Iris')) // { name: 'Iris', age: 10 }
console.log(makePerson('Iris', 24)) // { name: 'Iris', age: 24 }

색인 키와 값으로 객체 만들기

export type KeyValueType = {
  [key: string]: string
}

export const makeObject = (key: string, value: string): KeyValueType => ({[key]: value})

console.log(makeObject('name', 'Iris')) // { name: 'Iris' }
console.log(makeObject('firstName', 'Iris')) // { firstName: 'Iris' }

이번 스터디에서 특별히 좋았던 점이나 어려웠던 점, 새로 알게 된 부분

콜백 함수, 고차 함수 등 타입스크립트의 여러 함수 관련 문법들을 학습했다. 처음 읽어나가는 부분인 만큼 아직 이해가 잘 되지 않는 부분들이 있어 표시해둔 뒤 내일 복습하며 다시 한번 읽어보기로 했다.

profile
👩🏻‍💻 Web Front-end Developer

0개의 댓글