본문 바로가기
FRONTEND/Javascript

220801 Typescript Destructuring

by 또야또야 2022. 8. 1.
반응형

Typescript Destructuring

Array Destructing

const input = [1, 2]
const [first, second] = input
console.log(first)  // 1
console.log(second) // 2
function f ([first, second]: [number, number]) {
  console.log(first)  // 1
  console.log(second) // 2
}

f([1, 2])

... 문법을 이용한 방법입니다.

const [first, ...rest] = [1, 2, 3, 4]
console.log(first) // 1
console.log(rest)  // [2, 3, 4]
const [, second, , fourth] = [1, 2, 3, 4]
console.log(second) // 2
console.log(fourth) // 4

Tuple Destructing

const tuple: [number, string, boolean] = [7, 'hello', true]
const [a, b, c] = tuple

console.log(a, b, c) // 7 'hello' true

const [a, b, c, d] = tuple // Error, no element at index 3
const tuple: [number, string, boolean] = [7, 'hello', true]

const [a, ...bc] = tuple
console.log(a, bc) // 7 ['hello', true]

const [_a, b, c, ...d] = tuple
console.log(_a, b, c, d) // 7 'hello' true []
const tuple: [number, string, boolean] = [7, 'hello', true]

const [a] = tuple
const [, b] = tuple

console.log(a) // 7
console.log(b) // hello

Object destructing

const { a, b } = { a: 'baz', b: 101 }
console.log(a, b) // baz 101
const o = {
  a: 'foo',
  b: 12,
  c: 'bar'
}

const { a, ...passthrough } = o
const total = passthrough.b + passthrough.c.length // 15

Property Renaming

const o = {
  a: 'foo',
  b: 12,
  c: 'bar'
}

const { a: name1, b: name2 }: { a: string, b: number } = o
console.log(name1, name2) // foo 12

기본 값

function keepWholeObject (obj: { a: string, b?: number }) {
  // b 기본값은 1001
  let { a, b = 1001 } = obj
}

함수 선언 (Function declarations)

함수 타입 선언

type C = { a: string, b?: number }
function f ({ a, b }: C): void {
  // ...
}
function f ({ a, b = 0 } = { a: '' }): void {
  // ...
}

f({ a: 'yes' }) // default b = 0
f()             // OK, default to { a: '' }, default b = 0
f({})           // Error : 'a' is required if you supply an argument

Spread 연산자

const first = [1, 2]
const second = [3, 4]
const bothPlus = [0, ...first, ...second, 5]

console.log(bothPlus) // [0, 1, 2, 3, 4, 5]

const defaults = { food: 'spicy', price: '$$', ambiance: 'noisy' }
const search = { ...defaults, food: 'rich' }

console.log(defaults) // { food: 'spicy', price: '$$', ambiance: 'noisy' }
console.log(search)   // { food: 'rich', price: '$$', ambiance: 'noisy' }
반응형

댓글