본문 바로가기
front-end/TypeScript

[TS]02 readonly / Tuple / any 타입

by -제이리 2022. 5. 10.
728x90
320x100

readonly

- 읽기전용속성.  js에서는 없는 속성이다.

type Player = {
  readonly name: string, // 앞에 readonly를 적어주면 읽기전용으로 바뀐다.
  age?: number
}
const playerMaker = (name:string) : Player => ({name})
const player = playerMaker("Tom")
player.name = 'Jay' // 위에서 readonly속성을 주었기 때문에 수정하려고 시도하면 오류가 난다.

//배열에서 readonly 사용하기
const numbers: readonly number[] = [1, 2, 3]
number.push(1) // readonly속성을 가졌기 때문에 추가가 안되고 오류표시가 생긴다.

Tuple

-length와 type이 고정된 배열을 의미한다. js에서는 없는 속성이다.

- 코드를 저장하고 실제 production 환경으로 push하기 전에 오류를 확인할 수 있다.

 
const player: [string, number, boolean] = ['Tom', 1, true] // 순서에 맞는 타입을 가져야한다.

// readonly와 묶어서 쓸 수도 있다.
const player: readonly [string, number, boolean] = ['Tom', 1, true]

any

- any는 말그대로 any type를 쓰고 싶을때 사용한다.

- any를 사용하게 되면 타입스크립트를 벗어나 자바스크립트에 있는것이 된다. 즉 타입스크립트의 보호를 받지 못한다.

728x90
320x100

댓글