Search Terms
type guard store result const
Suggestion
Store the result of a type guard into a const but keep its "type guardiness".
Use Cases
Suppose I have some code containing a type guard:
public MyFunc($elem: JQuery | string): void {
if (!(typeof $elem === 'string')) {
// compiles ok
let $f = $elem.parents('form').first();
}
}
Here Typescript knows the $elem is not a string, so it must be a JQuery element, and the compiler is happy.
But say I want to store the result into a const (perhaps for readability and re-use of the expression)
public MyFunc2($elem: JQuery | string): void {
const elemIsString = (typeof $elem === 'string');
if (!elemIsString) {
// fails to compile, $elem is still "JQuery | string" here
let $f = $elem.parents('form').first();
}
}
Is such a thing possible without writing a type guard function? It seems like it could be possible if the result of (typeof $elem === 'string') is not boolean, but instead is of type $elem is string type guard (but is simply emitted as a JavaScript boolean)
Checklist
My suggestion meets these guidelines:
Search Terms
type guard store result const
Suggestion
Store the result of a type guard into a const but keep its "type guardiness".
Use Cases
Suppose I have some code containing a type guard:
Here Typescript knows the
$elemis not a string, so it must be a JQuery element, and the compiler is happy.But say I want to store the result into a const (perhaps for readability and re-use of the expression)
Is such a thing possible without writing a type guard function? It seems like it could be possible if the result of
(typeof $elem === 'string')is not boolean, but instead is of type$elem is stringtype guard (but is simply emitted as a JavaScript boolean)Checklist
My suggestion meets these guidelines: