Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- supabase authentication
- Spring
- Next.js
- code-push-standalone
- 코드푸시
- extends
- async
- xlsx-js-style
- javascript
- codepush
- 글또10기x코드트리
- app.post
- 슬라이딩윈도우
- reactnative
- TS
- Filter
- set
- generic
- supabase 페이지네이션
- interface
- 이진탐색
- map
- meatadata
- 타입스크립트
- 상속
- react
- array
- 페이지네이션
- supabase auth
- 스크롤이벤트
Archives
- Today
- Total
rhanziy
TS - rest 파라미터, destructuring type지정 본문
함수의 파라미터로 rest형식, 디스트럭쳐링형식이 들어왔을 때 type지정하는 방법.
일단 rest parameter는 파라미터가 몇개 들어올지 미리 정의를 할 수 없을 때 ... 으로 만들어주는거
function 전부더하기(...a){
console.log(a)
}
전부더하기(1,2,3,4,5)
console을 찍어보면 a값은 [ ] 어레이 안에 담겨져 있다.
function 전부더하기(...a : number[]){
console.log(a)
}
전부더하기(1,2,3,4,5)
그래서 타입지정도 array처럼 해주면 됨.
array나 object 괄호 벗길 때 사용하는 Spread operator와는 다르니 유의
rest parameter type지정 예시) 입력된 숫자들의 최대 값을 return하는 함수
function maxNum(...a :number[]) :number{
let max = 0;
a.forEach((e)=>{
if(max < e){
max = e;
}
})
return max;
}
maxNum(6,3,7,2);
destructuring 문법은 자바스크립트에서 array나 object안에 있는 데이터를 빼서 변수로 만들어 쓰고싶을 때 사용함.
let [a, b] = ['안녕', 100]
// a = '안녕', b = 100
let { student, age } = { student : true, age: 20 }
// student = true, age = 20
object자료형을 destructuring 할 땐 변수이름을 속성이름과 맞춰주자. 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 })
위 코드와 아래 코드 실행결과는 똑같다. type지정은 오브젝트 타입 지정하는 법과 같음.
let person = { student : true, age : 20 }
function 함수({ student, age } : { student : boolean, age : number }){
//이하생략
}
함수({ student : true, age : 20 })
destructuring 문법 type지정 예시
1. object자료형
type UserType = {
user : string,
comment : number[],
admin : boolean
}
function userInfo2({ user, comment, admin }: UserType ) :void{
console.log(user, comment, admin)
}
userInfo2({ user: 'kim', comment : [3, 5, 4], admin : false });
2. array 자료형
function arryParam([a,b,c] : (number|string|boolean)[]){
console.log(a,b,c);
}
arryParam([40, 'wine', false])
'Html_css_js' 카테고리의 다른 글
js - 선택한 이미지 미리보기 구현 (2) | 2023.09.06 |
---|---|
TS - interface 쉽게 작성하기(json데이터) (0) | 2023.03.13 |
TS - interface 로 type 키워드 구현 (0) | 2023.01.27 |
TS - class의 타입지정 (0) | 2023.01.27 |
AJAX로 서버에 DELETE 요청하는법, 요청에 응답하는 여러가지 방법 (0) | 2023.01.17 |