Created
August 2, 2019 14:03
-
-
Save OliverJAsh/6ff5494b4f3f04ca0cf4ef85f342e623 to your computer and use it in GitHub Desktop.
TypeScript narrowed union is lost inside function scopes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export type Foo = { | |
foo: string; | |
}; | |
export type Bar = { | |
bar: string; | |
}; | |
export type Value = Foo | Bar; | |
export declare const value: Value; | |
export declare const checkIsFoo: (value: Value) => value is Foo; | |
// Test (internal) | |
{ | |
const fn = (value: Value) => { | |
if (checkIsFoo(value)) { | |
const test1: Foo = value; | |
const fn = () => { | |
// No error, good | |
const test2: Foo = value; | |
}; | |
} | |
}; | |
} | |
{ | |
if (checkIsFoo(value)) { | |
const test1: Foo = value; | |
const fn = () => { | |
// No error, good | |
const test2: Foo = value; | |
}; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Explanation: | |
// https://github.com/microsoft/TypeScript/pull/8849 | |
// https://github.com/Microsoft/TypeScript/issues/9258 | |
import { checkIsFoo, Foo, Value, value } from './env'; | |
// Test (external) | |
{ | |
const fn = (value: Value) => { | |
if (checkIsFoo(value)) { | |
const test1: Foo = value; | |
const fn = () => { | |
// No error, good | |
const test2: Foo = value; | |
}; | |
} | |
}; | |
} | |
{ | |
if (checkIsFoo(value)) { | |
const test1: Foo = value; | |
const fn = () => { | |
// Unexpected error, bad | |
const test2: Foo = value; | |
}; | |
} | |
} | |
// Workaround | |
{ | |
if (checkIsFoo(value)) { | |
const foo = value; | |
const test1: Foo = foo; | |
const fn = () => { | |
// No error, good | |
const test2: Foo = foo; | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment