-
Notifications
You must be signed in to change notification settings - Fork 13.2k
Closed
Labels
DuplicateAn existing issue was already createdAn existing issue was already created
Description
Currently type guards are limited only to bodies of conditionals.
A simple example with 'if':
function f(s: string | number) {
if (typeof s === "string") {
// s is 'string'
}
else {
// s is 'number'
}
}But what if I write the same code, but another way:
function f(s: string | number) {
if (typeof s === "string") {
// s is 'string'
// do something
return;
}
// s is 'string | number', according to the compiler
// but control flow of 'if' block flows directly to a function exit
// that's why, s is actually 'number' here, if no assignments are made
}So, the suggestion is to augment the rule for 'if' as follows:
- If the false branch is not present, and all control flow exits of the true branch point exactly to function exits, the type of a variable or parameter is narrowed by a type guard in the code after 'if' statement when false, provided the code after 'if' statement contains no assignments to the variable or parameter.
- If all control flow exists of the false branch point exactly to function exits, the type of a variable or parameter is narrowed by a type guard in the code after 'if' statement when true, provided the code after 'if' statement contains no assignments to the variable or parameter.
Metadata
Metadata
Assignees
Labels
DuplicateAn existing issue was already createdAn existing issue was already created