본문 바로가기
IT/typescript

[Typescript] asserts를 이용한 타입 가드 활용

by 내일은교양왕 2024. 2. 5.

asserts 활용 (v3.7부터 가능)

function assert(value: any, errorMsg: string): asserts value {
    if(!value) throw new Error(errorMsg)
}

function toString(value? : number) {
    assert(value !== undefined, 'value should not be undefined')
    return value.toFixed(2)
}

console.log(toString(4), typeof toString(4)) // "4.00", "string"

 

https://fe-developers.kakaoent.com/

 

홈 | 카카오엔터테인먼트 FE 기술블로그

 

fe-developers.kakaoent.com

 

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

[Typescript] 타입 호환성  (0) 2024.02.22
[Typescript] Branded type  (0) 2024.02.21
[Typescript] 외부 패키지의 타입 치환  (1) 2024.02.05
[Typescript] index signature vs mapped type  (0) 2024.02.05
[Typescript] enum vs union  (0) 2024.02.05