TypeScript

[TypeScript] Rest, Destructuring Type

최성2 2022. 2. 25. 18:26

 

1. rest 파라미터 타입 지정

: rest 파라미터는 항상 array 안에 담겨오기 때문에, 타입도 array와 똑같이 지정 해주면 된다

 ...a: number[ ] 

 ...a: (number | string)[ ] 

function num(...a: number[]) { 👈
  console.log(a);
}

num(1,5,3,5,6,6)

//string, number 타입을 동시에 지정하고 싶을 때는 Union type 사용
function num(...a: (number | string)[]) { 👈
  console.log(a);
}

num(1,5,3,5,6,'안녕')

 

 

✅ rest는 spread와 다르다

...spread는 array, object 자료 왼쪽에, ...rest는 함수 선언시 소괄호 안에서 사용된다

 

*spread

: 배열이나 객체를 펼칠 때 사용, 새로운 객체를 만들 때 사용

let name = ["Sung2", "Choi"]

let n = [...name, 20, ...name]

console.log(n)
// ["Sung2", "Choi", 20, "Sung2", "Choi"]
let name = { first: "Sung2", last: "Choi" }

let n { ...name, age: '20'}

console.log(n);
// { first: "Sung2", last: "Choi", age: '20' }

 


 

2. Destructuring 타입 지정

: destructuring 문법도 함수 파라미터에 사용 가능하다

: array, object와 똑같이 타입 지정 해주면 된다

let person = { student : true, age : 20 }

function member({ student, age }: { student: boolean, age: number }){ 👈
  console.log(student, age) 
}
member(person) //true, 20

//or

interface Person { 👈
  student: boolean,
  age: number
}

let person: Person = { student : true, age : 20 }

function member({student, age}: Person): void{ 👈
  console.log(student, age)
}
member(person) //true, 20

 

*object destructuring 은 object 속성 명을 그대로 작명해야 편리하고, array destructuring 은 자유롭게 작명해도 된다

//array
type Age = (number | string | boolean)[]

function wineAge([x, y, z]: Age) { 👈
  console.log(x, y, z);
}

wineAge([40, 'wine', false])

 

 

 

✅ destructuring

: array, object 안에 있는 데이터를 변수로 만들고 싶을 때 사용

let person = { student : true, age : 20 }

let student = person.student
let age = person.age

// ===

let { student, age } = { student : true, age : 20 } 👈 //destructuring

 

 

 

Ref

https://codingapple.com/course/typescript-crash-course/

 

빠르게 마스터하는 타입스크립트 - 코딩애플 온라인 강좌

  누구나 마음 한켠엔 나만의 웹서비스를 만들고 싶어합니다. 프론트엔드는 어찌저찌 하겠는데 서버 만드는게 어렵고 귀찮다고요? 그렇다면 Firebase를 쓰십시오.   구글이 웹서버를 대신 만들어

codingapple.com

 

'TypeScript' 카테고리의 다른 글

[TypeScript] Never  (0) 2022.03.03
[TypeScript] Narrowing ++  (0) 2022.03.03
[TypeScript] Interface  (0) 2022.02.23
[TypeScript] Strict, HTML 조작할 때 주의점  (0) 2022.02.19
[TypeScript] Function, Method alias Types  (0) 2022.02.18