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 (0) | 2024.02.03 |
---|---|
Generic Programming and Type Parameter (1) | 2023.11.12 |
Static and non-static(instance) methods (1) | 2023.11.12 |
NestJs - Mircoservices (2) | 2023.11.08 |
How to do a code review (0) | 2023.11.03 |