Typescript Type narrowing

2023. 11. 12. 16:27·개발

Typescript's type narrowing

- TypeScript has a feature called "type narrowing" which allows the type system to refine the type of variable based on certain checks. For example, if you check whether a variable is not null, TypeScript understands in the subsequent code that this variable is indeed not null.

 

Mutaillity of Obejcts

- In JavaScript , obejcts are mutable. THis means that their properties can be changed at any time. If you have an object and you check one of its properties, there is no guarantee that this property won't be changed by some other part of the program before we use it again.

 

TypeScript's conservatism with Obejct Properties

When you perform runtime check on an object's properyy. TypeScript's static analysis doesn't always narrow down the type of that property in subsequent code. This is because, theoretically, the property could be modified by other parts of the program between the check and its use.

 

For instance, let's check this code

if (patchUserSettingRequest.timezoneIdentifier) {
    updateUserTimezoneSetting(patchUserSettingRequest.timezoneIdentifier); // TypeScript is cautious here
}

 

Even though I've checked "patchUserSettingRequest.timezoneIdentifier" for truthiness, TypeScript remains cautious.

 

From its perspective, since patchUserSettingRequest is mutable, timezoneIdentifier could be changed to 'null' or 'undefined' by some other code between the check and the call to updateUserTimezoneSetting.

 

To sum it up

From the example given, TypeScript is concerned that patchUserSettingRequest.timezoneIdentifier might be modified to 'undefined' or 'null' between my if-check and where I use it later.

 

 

Solution

1. Use a local variable:  Assign the property to a local variable within the scope of the check. TypeScript is more confident about the immutabillity of local variables within a limited scrope.

 

2. Use Non-null Assertion Operator("!") :  Assert to Typescript that sure the value isn't "null" or "undefined" at the point of use. This tells TypeScript to trust our judgement, though it bypasses its safety checks.

(But I do not recommend this way )

저작자표시 비영리 (새창열림)

'개발' 카테고리의 다른 글

Typescript Custom Decorator  (3) 2024.02.03
Generic Programming and Type Parameter  (1) 2023.11.12
Static and non-static(instance) methods  (3) 2023.11.12
NestJs - Mircoservices  (2) 2023.11.08
How to do a code review  (1) 2023.11.03
'개발' 카테고리의 다른 글
  • Typescript Custom Decorator
  • Generic Programming and Type Parameter
  • Static and non-static(instance) methods
  • NestJs - Mircoservices
senyalog
senyalog
개발 블로그 https://github.com/iamyunjuda
  • senyalog
    Senya의 개발 블로그
    senyalog
  • 전체
    오늘
    어제
    • 분류 전체보기 (71)
      • 일상 (6)
      • 알고리즘 이론 (14)
        • 백준 (8)
      • 개발 (31)
        • Server (8)
        • 인턴 (2)
        • Javascript (0)
      • 경제 (7)
  • 블로그 메뉴

    • Github
    • 홈
  • 링크

    • Github
  • 공지사항

  • 인기 글

  • 태그

    인턴
    MSA
    서버
    GIT
    암호화페
    이마고웍스
    백준풀이
    일상
    알고리즘공부
    백준
    nestjs
    인턴생활
    공부
    깃
    TypeScript
    생각
    대학생
    컴공
    카페
    대학생인턴
    개발
    코딩테스트
    백엔드
    알고리즘
    개발자
    공대생
    코딩
    개발공부
    경제
    백준문제
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
senyalog
Typescript Type narrowing
상단으로

티스토리툴바