타입스크립트의 타입#2

유재헌·2023년 1월 31일
0

Typescript

목록 보기
3/8

1. readonly

type Player = {
  readonly name: string,
  age?: number
}

const playerMaker = (name: string) :Player => ({name])

const jaehun = playerMaker("jaehun")
jahun.name = "messi" //-> error

const numbers : readonly number[] = [1, 2, 3, 4]
numbers.push(5) // -> 불가능

readonly를 통해 읽기전용으로 만들 수 있다.
최초선언 후 수정 불가


2. Tuple

const player : [string, number, boolean] = ["jaehun", 2, true]

player[0] = 1 //->error

Typescript에게 이 array가 최소 3개의 아이템을 가지며 string, number, boolean의 순서대로여야 함을 알려야 할 때 유용하다.

tuple은 array를 생성할 수 있게 한다. 최소한의 길이를 가져야 하고 특정위치에 특정 타입이 있어야 한다.


3. Undefined
let a : undefined = undefined

4. null
let a : null = null

5. any
  • 아무 타입이나 될 수 있음.
  • 비어있는 값을 쓰면 기본값이 any가 됨.
  • Typescript의 보호장치로부터 빠져나오고 싶을 때 사용
let a = []

6. void
  • void란 비어있는 것을 말함.
  • 아무것도 return하지 않는 함수의 반환값을 나타낸다.
  • 함수에 return 문이 없거나 해당 return 문에서 명시적 값을 반환하지 않을 때 항상 유추되는 타입이다.
function hello() {
  console.log("hello");
}

hello함수에 커서를 갖다대면 아무것도 return하지 않는 void라는 것을 알려준다.
Typescript는 그 함수가 아무것도 return하지 않는다는 것을 자동으로 인식한다.때문에 hello() : void 이렇게 쓰지 않아도 된다.


7. never
  • 함수가 절대로 return하지 않을 때 발생한다.
  • 타입이 두가지 일 수도 있는 상황에 발생한다.
function hello(name: string | number) {
  if(typeof name === "string") {
    name
    //커서를 올려보면 name은 string
  } else if(typeof name === "number") {
    name
    //name은 number
  } else {
    name
    //name은 never
    //뭘쓰던 그 타입은 never
    //이 코드는 절대 실행되지 않아야 한다는 것.
  }
}

8. unknown
let a : unknown
  • 어떤 변수의 타입을 미리 알지 못하는 경우.
  • 어떤 작업을 하려면 이 변수의 타입을 먼저 확인해야 하도록 하는 일종의 보호장치.
if(typeof a === 'number') {
  let b = a + 1;
}

위 if구문 안에서는 a의 타입이 number이기 때문에 error없이 코드를 작성할 수 있다.

if(typeof a === "string") {
  let b = a.toUpperCase();
}

위 if구문 안에서는 a의 타입이 string이기 때문에 error없이 코드를 작성할 수 있다.

profile
possibilities

0개의 댓글