Closed
Description
Bug Report
🔎 Search Terms
type guard
🕗 Version & Regression Information
TypeScript 3.3.3+ (as per playground)
Please keep and fill in the line that best applies:
- This is the behavior in every version I tried, and I reviewed the FAQ for entries about Common "Bugs" That Aren't Bugs
⏯ Playground Link
Playground link without error but with incorrect type
💻 Code
The compiled JavaScript version works correctly, but TypeScript gives errors:
type EmptyString = '' | null | undefined;
function isEmpty(value: string | EmptyString): value is EmptyString {
return value === '' || value === null || value === undefined;
}
let test: string | null | undefined;
if (isEmpty(test)) {
if (test === '') { // Compilation error since test: null | undefined and not test: '' | null | undefined
console.log('Nope');
}
}
Also, it's weird that when I remove null from the list of types, the error disappears, but the incorrect type is still shown:
type EmptyString = '' | undefined;
function isEmpty(value: string | EmptyString): value is EmptyString {
return value === '' || value === undefined;
}
let test: string | undefined;
if (isEmpty(test)) {
if (test === '') { // No errors, but the editor displays incorrect type.
console.log('Nope');
}
}
🙁 Actual behavior
TypeGuard ignores empty string and thinks the value can only be null or undefined.
🙂 Expected behavior
The type should include empty string. No errors expected.