Skip to content

Type narrowing doesn't work as expected in templates in Angular 13 #44353

@th0r

Description

@th0r

Which @angular/* package(s) are the source of the bug?

compiler

Is this a regression?

Yes

Description

Angular 12 allowed to use type-narrowing methods in component templates, but Angular 13 shows compilation error in the following case:

class SomeComponent {
  asyncData?: {foo: string};
  
  isDataLoaded(): this is Required<SomeComponent> {
    return Boolean(this.asyncData);
  }
}
<ng-container *ngIf="isDataLoaded()">
  <!-- This compiled successfully in Angular 12 but throws compilation error in Angular 13 -->
  {{ asyncData.foo }}
</ng-container>

I've created a reproduction repo - just run npm start and you'll see compilation error.

Please provide a link to a minimal reproduction of the bug

https://github.com/th0r/ng-13-templates-type-narrowing-bug

Please provide the exception or error you saw

Error: src/app/app.component.html:2:14 - error TS2322: Type 'PageData | undefined' is not assignable to type 'PageData'.
  Type 'undefined' is not assignable to type 'PageData'.

2   <app-page [data]="pageData"></app-page>
               ~~~~

  src/app/app.component.ts:15:16
    15   templateUrl: './app.component.html',
                      ~~~~~~~~~~~~~~~~~~~~~~
    Error occurs in the template of component AppComponent.

Please provide the environment you discovered this bug in (run ng version)

Angular CLI: 13.0.4
Node: 14.17.3
Package Manager: npm 6.14.15
OS: darwin x64

Angular: 13.0.3
... animations, common, compiler, compiler-cli, core, forms
... platform-browser, platform-browser-dynamic, router

Package                         Version
---------------------------------------------------------
@angular-devkit/architect       0.1300.4
@angular-devkit/build-angular   13.0.4
@angular-devkit/core            13.0.4
@angular-devkit/schematics      13.0.4
@angular/cli                    13.0.4
@schematics/angular             13.0.4
rxjs                            7.4.0
typescript                      4.4.4

Anything else?

No response

Metadata

Metadata

Assignees

Labels

P3An issue that is relevant to core functions, but does not impede progress. Important, but not urgentarea: compilerIssues related to `ngc`, Angular's template compilercompiler: template type-checkingstate: has PR

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions