rest 파라미터
function 함수(...a:number[]){
console.log(a)
}
함수(1,5,3,5,6,6)
... 키워드로 표현하며 파라미터의 개수를 예측하기 어려운 경우 사용
1. rest 파라미터는 일반 파라미터 뒤에만 올 수 있다.
2. rest 파라미터 자리에 넣은 값은 [ ] array 안에 모두 담겨있다.
spread 오퍼레이터
let arr = [1,2,3];
let arr2 = [4,5];
let arr3 = [...arr, ...arr2];
console.log(arr3)
... 키워드로 rest 파라미터와 표현방식은 동일.
하지만 파라미터로 주는 값이 아니라, array나 object에 사용한다.
1. 위치는 상관없이 사용할 수 있다.
2. 괄호를 벗겨준다는 의미로 해석하면 이해가 쉽다.
=> 즉 arr [1,2,3]을... arr로 할당하면 1,2,3을 뜻하는 것이다.
arr3은 1,2,3,4,5가 array안에 담겨있음을 짐작할 수 있다.
destructuring 문법
let 사람 = { student : true, age : 20 }
let student = 사람.student;
let age = 사람.age
보통 array, object에 들어있는 값이 필요할 때,
변수명.data 방식으로 값을 꺼내는데, 이 불편함을 덜기 위해
destructuring 문법을 사용한다.
let { student, age } = { student : true, age : 20 } //object
let [a, b] = ['안녕', 100] //array
변수명을 기입하는 곳에 object는 { }, array는 [ ] 안에 속성명과 같게 할당하는 방법이다.
1. object의 경우 변수명을 속성명과 맞추는 것이 편리함.
2. array의 경우는 변수명을 편하게 작명 가능.
함수 파라미터 + destructuring 문법
let person = { student : true, age : 20 }
function 함수(a, b){
console.log(a, b)
}
함수(person.student, person.age)
기존방식
=> 변수. 속성으로 값을 가져옴.
function 함수({student, age}){
console.log(student, age)
}
함수({ student : true, age : 20 })
destructuring 방식
=> object는 { }, array는 [ ]를 사용하여 속성명을 파라미터에 작성
리액트과정에서 rest파라미터랑 spread 오퍼레이터는 익히 알고 있는 문법이라 다가가기 편했지만,
destructuring 문법은 되게 생소하게 다가왔다.
항상 안에 있는 속성값을 꺼낼 때는 a.data 느낌으로 가져오는 게 손에 익은 탓일까,
아직까지는 기존방식이 편하긴한데 개발자들이 불편해서 개발한 문법이라는게 되게 웃겼다.
쓰다 보면 편해질 날이 오겠지!
'TypeScript' 카테고리의 다른 글
public, private 키워드 (0) | 2023.07.03 |
---|---|
Narrowing 추가적인 방법들 (0) | 2023.07.03 |
interface vs type (0) | 2023.07.03 |
함수 및 methods에 type alias 사용법 (0) | 2023.07.03 |
Literal Types (0) | 2023.07.03 |