TypeScript -2-

mh·2022년 5월 2일
0

TypeScript

목록 보기
2/17
post-thumbnail

Photo by Bailey Gullo on Unsplash

readonly Property

type Name = string;
type Age = number;

type Player = {
    readonly name:Name,
    age?:Age
}

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

const bob = playerMaker("bob")
bob.age = 7
bob.name = "star"
  • Plyaer의 name을 수정하려고 시도하면 TypeScript에서 에러발생해서 막음

  • 배열에 readonly를 붙였을때

const numbers: readonly number[] = [1,2,3,4]
numbers.push(1) //error

const names: readonly string[] = ["1", "2"]
names.push() //error

  • immuatability(불변성)을 가지게 됨
  • map, filter 와 같은 메소드들은 배열을 변경하지 않으므로 사용가능

Tuple

Tuple?

  • 배열을 생성함
  • 길이를 가지고 있어야 함
  • 특정 위치에 특정 타입이 있어야 함

이러한 배열을

//이름,나이,챔피언인지아닌지
["bob",7,true]

타입스크립트로 표현해보기

const plyaer: [string, number, boolean] = []

  • 에러: 3개의 요소가 필요한데 0개임, 그러니 타입[]은 [string,number,boolean]타입에 할당 할 수 없음
  • 이 타입은 3개의 요소가 필요하고 string, number, boolean 순서여야 한다는 보호장치를 마련

const player: [string,number,boolean] = ["bob",7,true]

  • 정해진 갯수와 순서를 갖는 요소를 가지는 array를 지정할 수 있음
  • 이런 값들을 주는 API를 처리할때 유용
player[0]= 1

readonly 와 같이 쓰기

const player: readonly[string, number, boolean] = ["bob",7,true]
player[0] = "hi"

  • JavaScript는 튜플이 없어서 이렇게 보임

  • TypeScript는 실제 프로덕션 환경으로 푸쉬하기 전에 오류확인이 가능

JavaScript도 가지고 있는 타입들

  • undefined 와 null
let a: undefined = undefined;
let b: null = null;
  • 여기서 age? 는 number || undefined 의 단축임
type Player = {
  age?:number
}

any

비어있는 값들을 쓰면 기본값이 any

let a = []
//let a: any[]
  • TypeScript로부터 빠져나오고 싶을때 사용
  • 아무타입이나 허락해줌
  • any사용을 막기위해 설정할 수 있는 typescript 설정들이 있음

그럼에도 불구하고 사용할 필요가 있음

  • 좋지 않은 예
const a : any[] = [1,2,3,4]
const b : any = true

a + b

-> 가능함 -> any 타입이기 때문

타입스크립트의 보호장치를 모두 비활성
하지만 필요 할때가 있음

const a : = [1,2,3,4]
const b : = true

a + b

->오류

정리

배운것들

  • readonly
  • Tuple, readonly Tuple
  • any
profile
🤪🤪🤪🤪🤪

0개의 댓글