-
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
Type narrowing with interface inheritance #12295
Comments
That isn't narrowing, that is "magical" widening... You asserted export interface SyncCmd {
name: string;
}
export interface SyncCmdFoo extends SyncCmd {
name: 'Foo';
contentFoo: string;
}
// You need to tell TypeScript the widest set of types, so it can then narrow them
const command: SyncCmd | SyncCmdFoo = {name: 'Foo', contentFoo: 'hello'};
switch (command.name) {
case 'Foo':
alert(command.contentFoo);
break;
default:
break;
} |
OK, understood. Thanks. |
@kitsonk @HolgerJeromin it will not work in latest TS - command will not be narrowed to const command: SyncCmd | SyncCmdFoo = {name: 'Foo', contentFoo: 'hello'};
switch (command.name) { // <- Type: SyncCmd | SyncCmdFoo, at playground type: SyncCmdFoo
case 'Foo':
alert(command.contentFoo); // <- Type: SyncCmd | SyncCmdFoo
break;
default:
break;
} We would need to have ability to provide: export interface SyncCmd {
name: string - 'Foo';
} for it to work |
I removed the |
@kitsonk There the map has value type Am I misunderstanding? I guess it needs to narrow based on |
TypeScript Version: 2.0.3
This is related to discriminated unions, but with interface inheritance.
I get a SyncCommand via XHR and need to do different stuff depending on the command.
Right now i need a Type assertions for that, but my interface definition holds all information already.
Code
Expected behavior:
Inside the 'Foo' case the type should be narrowed to SyncCmdFoo.
The text was updated successfully, but these errors were encountered: