Skip to content

Instantly share code, notes, and snippets.

@OliverJAsh
Created August 2, 2019 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save OliverJAsh/6ff5494b4f3f04ca0cf4ef85f342e623 to your computer and use it in GitHub Desktop.
Save OliverJAsh/6ff5494b4f3f04ca0cf4ef85f342e623 to your computer and use it in GitHub Desktop.
TypeScript narrowed union is lost inside function scopes
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;
};
}
}
// 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