const assertion

Bonggus·2021년 12월 10일
0

타입스크립트

목록 보기
1/1

assertion?

  • 단언? 이라고 보는게 좋을듯하다

const assertion

  • let 변수에 대해서도 const 변수를 사용할 때와 같은 타입 추론 규칙을 적용할 수 있다
  • as const라는 키워드로 타입 단언을 하면 된다.
let hello = 'world' as const
// in ts
let hello = <const>'world'
hello = 'earth' // 컴파일 타임 에러 

객체에 대한 const assertion

  • 객체에 대입해서 타입추론을 해보면
const obj = {
	hello: 'world'
}
/*
const obj = {
	hello: string
}
*/
  • const로 선언되어도, 객체 내부 속성에 대한 타입은 넓은 범위로 추론된다
  • 왜냐면, const는 재할당이 안될뿐, 객체 내부의 값의 변경은 가능하기 때문
  • 이럴 경우 as const를 통해 타입 추론의 범위를 좁힐 수 있다
// hello만 assertion
const obj = {
  hello: 'world' as const,
  foo: 'bar'
}

// 모든 속성에 대해 assertion
const obj = {
  hello: 'world',
  foo: 'bar'
}  as const

  • 결과는 readonly 속성이 된다.

출처

profile
프론트엔드

0개의 댓글