fix(language-service): determine correct type for ngFor exported values (#34089)
Currently, variables of an unknown type in an `*ngFor` expression are refined to have the type of the iterable binding of the `*ngFor` expression. Unfortunately, this is a bug for variables aliasing [values exported by `*ngFor`](https://angular.io/api/common/NgForOf#local-variables), including `index` and `first`, because they are also given the type of the binding expression, but they are not of the binding type. For example, in ```typescript @Component({ selector: 'test', template: ` <div *ngFor="let hero of heroes; let i = index; let isFirst = first"> {{ hero }} </div> ` }) export class TestComponent { heroes: Hero[]; } ``` The local variables `i` and `isFirst` are determined to have a type of `Hero`, when actually their types are `number` and `boolean`, respectively. This commit fixes this bug by checking if the value of a variable in an `*ngFor` expression is known to be an export and assigning the variable the type of that export value. Only if the variable does not alias an export is it typed with the binding value of the `*ngFor` expression. Closes https://github.com/angular/vscode-ng-language-service/issues/460 PR Close #34089
This commit is contained in:
@ -127,6 +127,31 @@ describe('diagnostics', () => {
|
||||
expect(diags).toEqual([]);
|
||||
});
|
||||
|
||||
describe('diagnostics for ngFor exported values', () => {
|
||||
it('should report errors for mistmatched exported types', () => {
|
||||
mockHost.override(TEST_TEMPLATE, `
|
||||
<div *ngFor="let hero of heroes; let i = index; let isFirst = first">
|
||||
'i' is a number; 'isFirst' is a boolean
|
||||
{{ i === isFirst }}
|
||||
</div>
|
||||
`);
|
||||
const diags = ngLS.getDiagnostics(TEST_TEMPLATE);
|
||||
expect(diags.length).toBe(1);
|
||||
expect(diags[0].messageText).toBe(`Expected the operants to be of similar type or any`);
|
||||
});
|
||||
|
||||
it('should not report errors for matching exported type', () => {
|
||||
mockHost.override(TEST_TEMPLATE, `
|
||||
<div *ngFor="let hero of heroes; let i = index">
|
||||
'i' is a number
|
||||
{{ i < 2 }}
|
||||
</div>
|
||||
`);
|
||||
const diags = ngLS.getDiagnostics(TEST_TEMPLATE);
|
||||
expect(diags.length).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('diagnostics for invalid indexed type property access', () => {
|
||||
it('should work with numeric index signatures (arrays)', () => {
|
||||
mockHost.override(TEST_TEMPLATE, `
|
||||
|
Reference in New Issue
Block a user