You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
user-defined type guards, type predicates, type narrowing, object properties
Suggestion
TS can narrow object types in if statements and other conditional control flows by various means. Particularly, if the object's type is a union type distinguishable by a "tag" (like Option<T> in the below example), we can narrow the type by checking the value of the tag. However, if the check for the tag is done by user-defined type guards against the property (but not the object itself), the object's type is not narrowed.
The suggestion is to make it work even if user-defined type guards are applied to object properties
Use Cases
The "tagged union" pattern is widely used in TS codebases. If tags theirselves are so complicated, we want to utilize user-defined type guards to check them.
Examples
typeOption<T>={type: "some"value: T}|{type: "none"}constisSome=(type: "some"|"none"): type is "some"=>type==="some"declareconstoption: Option<number>// Good: option is narrowed in the if blockif(option.type==="some"){option.value}// Bad: option isn't narrowedif(isSome(option.type)){// Error: Property 'value' does not exist on type 'Option<number>'.option.value}// Available workaroundconstisSomeObject=<T>(option: Option<T>): option is Extract<Option<T>,{type: "some"}>=>option.type==="some"if(isSomeObject(option)){option.value}
Search Terms
user-defined type guards, type predicates, type narrowing, object properties
Suggestion
TS can narrow object types in
if
statements and other conditional control flows by various means. Particularly, if the object's type is a union type distinguishable by a "tag" (likeOption<T>
in the below example), we can narrow the type by checking the value of the tag. However, if the check for the tag is done by user-defined type guards against the property (but not the object itself), the object's type is not narrowed.The suggestion is to make it work even if user-defined type guards are applied to object properties
Use Cases
The "tagged union" pattern is widely used in TS codebases. If tags theirselves are so complicated, we want to utilize user-defined type guards to check them.
Examples
playground
Checklist
My suggestion meets these guidelines:
The text was updated successfully, but these errors were encountered: