Closed
Description
TypeScript Version: 3.3.0, and the version on TS playground (3.4.1 as of this writing)
Search Terms: typeguard, empty string literal, undefined, union
Code
//--strictNullChecks
type Falsy<T> = (
| Extract<0, T>
| Extract<
(
| false
| null
| undefined
//Actually, only 0|NaN
//But TS does not support NaN literal
| number
| ""
| 0n
| HTMLAllCollection
),
T
>
);
declare const emptyStrOrUndefined: Falsy<string | undefined>;
declare function isFalsy<T>(
mixed: T
): mixed is Falsy<T>;
declare const s: string | undefined;
/*
Hovering over this isFalsy() call gives me,
function isFalsy<string | undefined>(mixed: string | undefined): mixed is "" | undefined
This is as expected
*/
if (isFalsy(s)) {
//Expected: s should be ""|undefined now
//Actual: s is undefined
if (s == undefined) {
//Should be undefined now
console.log(s);
} else {
//Expected: Should be "" now
//Actual: s is `never`
//Property 'length' does not exist on type 'never'.
console.log(s.length);
}
}
declare function isEmptyStrOrUndefined(mixed: any): mixed is "" | undefined;
if (isEmptyStrOrUndefined(s)) {
//Expected: s should be ""|undefined now
//Actual: s is undefined
if (s == undefined) {
//Should be undefined now
console.log(s);
} else {
//Expected: Should be "" now
//Actual: s is `never`
//Property 'length' does not exist on type 'never'.
console.log(s.length);
}
}
Expected behavior:
s
should be ""|undefined
where marked.
Also, unrelated, but this is where I would have liked a NaN
literal in TS =/
Actual behavior:
s
is undefined
Playground Link: Here
Related Issues: Not that I could find