@switch type narrowing doesn't work #52077
Copy link
Copy link
Closed
Labels
area: compilerIssues related to `ngc`, Angular's template compilerIssues related to `ngc`, Angular's template compilercompiler: template type-checkingstate: has PR
Milestone
Description
Which @angular/* package(s) are the source of the bug?
compiler
Is this a regression?
No
Description
interface Base {
type: 'foo' | 'bar'
}
interface Foo extends Base {
type: 'foo';
foo: string;
}
interface Bar extends Base {
type: 'bar';
bar: number;
}
@Component({
selector: 'app-root',
standalone: true,
template: `
@switch (v.type) {
@case ('bar') {
{{ v.bar }}
}
@case ('foo') {
{{ v.foo }}
}
@default {
Default
}
}
`
})
export class AppComponent {
v: Foo | Bar = { type: 'foo', foo: 'foo' };
}
Please provide a link to a minimal reproduction of the bug
No response
Please provide the exception or error you saw
No response
Please provide the environment you discovered this bug in (run ng version)
No response
Anything else?
It should work similar to typescript code.
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
area: compilerIssues related to `ngc`, Angular's template compilerIssues related to `ngc`, Angular's template compilercompiler: template type-checkingstate: has PR
Activity
JoostK commentedon Oct 6, 2023
The reason this doesn't work is because the TCB contains a parenthesized expression as switch-condition, which is not accounted for in TS's CFA.
ArielGueta commentedon Oct 7, 2023
It should be fixed, right?
crisbeto commentedon Oct 7, 2023
It might be worth changing switch to use if statements in the TCB as well.
crisbeto commentedon Oct 8, 2023
Confirmed Joost's explanation here: https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgEJwM4oN4ChnJgCeADhAFzIDkMA9rVcgD7UBGcUVuAvrrqJFiIUAMXrIIAD0ggAJhjSYc+QqQrU6DANwrNlDGCigA5jt79w0eEkVQJ0iHIXosyPAWJlKVdpx0FfShAAVwBbVmgzPhhgkAQwYFoQZGMIMAA1AAoASkoxWmZbNxUCKDTgqGSQgBtqgEIo3AQkg2QAN2QAXhS0rOydXAB6QeQAdVooAGsMXAwAd2AwBAALZEy2gDpPCGziggQlNg4qchLkZpAMWmqIDeraY3WN336z1jK4SYH9w5p6E7OFyuNzuDyemleBACHy+PD4w2QABFaBAFCBaGBkHMJpNZgslqtMk9ttldu5zr9fACoecWtdbvdHpsXv4oe8IJ9vhTXH8GKcaUD6aCmRsIazoRzYdwgA
JeanMeche commentedon Oct 9, 2023
FWIW the root issue is fixed on TS' side microsoft/TypeScript#56035
crisbeto commentedon Oct 9, 2023
I think we'll still have to keep the workaround around until we drop support for TS 5.2.
angular-automatic-lock-bot commentedon Nov 9, 2023
This issue has been automatically locked due to inactivity.
Please file a new issue if you are encountering a similar or related problem.
Read more about our automatic conversation locking policy.
This action has been performed automatically by a bot.
fix(compiler): work around TypeScript bug when narrowing switch state…
fix(compiler): work around TypeScript bug when narrowing switch state…