-
Notifications
You must be signed in to change notification settings - Fork 12.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
switch doesn't narrow object property for passing as function parameter #49153
Comments
This is working as intended: |
As @jcalz says, you must make your array item type a discriminated union: A workaround could be: export const Kind = {
FOO: 'FOO',
BAR: 'BAR',
} as const;
export type Kind = typeof Kind[keyof typeof Kind];
type Foo = { kind: typeof Kind.FOO };
type Bar = { kind: typeof Kind.BAR };
function extractFoo(obj: Foo): string {
return 'foo';
}
function extractBar(obj: Bar): string {
return 'bar';
}
function main() {
- const arr: Array<{ kind: Kind }> = [];
+ const arr: Array<Kind extends infer U ? U extends unknown ? { kind: U } : never : never> = [];
const values = arr.map(item => {
switch (item.kind) {
case Kind.FOO: {
const kind: typeof Kind['FOO'] = item.kind; // no error
return extractFoo(item); // no error!
}
case Kind.BAR: {
return extractBar(item); // no error!
}
}
})
} |
Thanks to you both for pointing me in the right direction. I guess I need to work on my "GH issue"-foo. 😆 |
Bug Report
🔎 Search Terms
narrow switch, discriminate switch, refine switch
🕗 Version & Regression Information
crashes on 3.5.x and above. Before this I couldn't run the playground because
as const
wasn't available. However, similar behavior happens when using enums (will include 2nd playground)⏯ Playground Link
Playground link with relevant code using as const
Playground link with relevant code using enum
💻 Code
🙁 Actual behavior
Error on extractFoo & extractBar
🙂 Expected behavior
item
should be a valid parameter to extractFoo/extractBar because thekind
property should be narrowed/refined by the switch statement.The text was updated successfully, but these errors were encountered: