본문 바로가기
IT/typescript

[typescript] as const

by 내일은교양왕 2024. 6. 3.

https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-4.html#const-assertions 를 읽고 정리한 글입니다.


 

as const를 선언하면,

 - string에서 'hello'로 추론됨 (아래 코드 확인)

 - obejct는 readonly로 설정

 - array는 readonly tuples로 변경

 

let x = ‘hello’ // string으로 추론
let x = ‘hello’ as const // hello으로 추론

let y = [10, 20] // number[]으로 추론
let y = [10, 20] as const // readonly [10, 20]으로 추론

let z = { text: 'hello' } // { text: string } 으로 추론
let z = { text: 'hello' } as const // { readonly text: 'hello' } 으로 추론


const ScrollDirection = {
  Up: 0,
  Down: 1,
  Left: 2,
  Right: 'right',
} as const

// 'Up' | 'Down' | 'Left | 'Right' 으로 추론 (as const가 없어도 같음)
type Key = keyof typeof ScrollDirection 

// 0 | 1 | 2 | 'right' 으로 추론 (as const가 없으면 string | number로 추론)
type value = (typeof ScrollDirection)[Key]

 

 

특징

단순한 리터널 표현에서만 가능

동적으로 계산되는 값에서는 사용 할 수 없음

// Error! A 'const' assertion can only be applied to a
// to a string, number, boolean, array, or object literal.
let a = (Math.random() < 0.5 ? 0 : 1) as const;
let b = (60 * 60 * 1000) as const;

// Works!
let c = Math.random() < 0.5 ? (0 as const) : (1 as const);
let d = 3_600_000 as const;

'IT > typescript' 카테고리의 다른 글

[typescript] is  (1) 2024.06.12
[typescript] in  (0) 2024.06.12
[clean code] 놓치기 쉬운 것들  (0) 2024.04.22
[typescript] Union & Intersection  (1) 2024.03.17
[Typescript] Type Assertion  (1) 2024.03.16