본문 바로가기

Learn/Typescript

Typescript tuple type

Tuple

array에 붙일 수 있는 타입

자료의 위치까지 정확히 지정할 수 있는 타입

 

let 멍멍이 :[string, boolean];
멍멍이 = ['dog', true]

Tuple 응용 : rest parameter

function 함수(...x :[string, number] ){
    console.log(x)
  }
  함수('kim', 123)  //가능
  함수('kim', 123, 456)  //에러
  함수('kim', 'park')  //에러

 rest parameter에 타입을 넣는 것도 가능하다.

 

 

type 함수 = [string[],number[]]

function 함수(...x : (number|string)[]) {
    let result : 함수 = [[],[]]
    for(let i = 0; i<x.length; i++){
        if(typeof i === "string"){
            result[0].push(i)
        } else {
            result[1].push(i)
        }
    }
    return result
}

이런식으로 새로운 배열을 만들 때도 응용이 가능하다.

 

 매우 강한 억제력을 갖고 있는 타입이라 함부로 사용하면 안될 것 같지만
자료를 통제하기 위해서 사용할 때는 매우 유용할 것 같다.

 

'Learn > Typescript' 카테고리의 다른 글

Typescript로 블록체인 만들기  (0) 2023.07.20
<노마드 TS 챌린지> 1주 차 회고  (0) 2023.07.02