Skip to content

Commit

Permalink
fix(compiler-cli): accept nullish coalescing operator for any and unk…
Browse files Browse the repository at this point in the history
…nown types (#44862)

We should not make assumptions about the any and unknown types; using a nullish
coalescing operator is acceptable for those.

PR Close #44862
  • Loading branch information
JoostK authored and thePunderWoman committed Jan 31, 2022
1 parent 25f8305 commit 0778e6f
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 1 deletion.
Expand Up @@ -35,6 +35,12 @@ class NullishCoalescingNotNullableCheck extends
return [];
}
const typeLeft = symbolLeft.tsType;
if (typeLeft.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown)) {
// We should not make assumptions about the any and unknown types; using a nullish coalescing
// operator is acceptable for those.
return [];
}

// If the left operand's type is different from its non-nullable self, then it must
// contain a null or undefined so this nullish coalescing operator is useful. No diagnostic to
// report.
Expand Down
Expand Up @@ -74,6 +74,42 @@ runInEachFileSystem(() => {
expect(diags.length).toBe(0);
});

it('should not produce nullish coalescing warning for the any type', () => {
const fileName = absoluteFrom('/main.ts');
const {program, templateTypeChecker} = setup([{
fileName,
templates: {
'TestCmp': `{{ var1 ?? 'foo' }}`,
},
source: 'export class TestCmp { var1: any; }'
}]);
const sf = getSourceFileOrError(program, fileName);
const component = getClass(sf, 'TestCmp');
const extendedTemplateChecker = new ExtendedTemplateCheckerImpl(
templateTypeChecker, program.getTypeChecker(), [nullishCoalescingNotNullableFactory],
{} /* options */);
const diags = extendedTemplateChecker.getDiagnosticsForComponent(component);
expect(diags.length).toBe(0);
});

it('should not produce nullish coalescing warning for the unknown type', () => {
const fileName = absoluteFrom('/main.ts');
const {program, templateTypeChecker} = setup([{
fileName,
templates: {
'TestCmp': `{{ var1 ?? 'foo' }}`,
},
source: 'export class TestCmp { var1: unknown; }'
}]);
const sf = getSourceFileOrError(program, fileName);
const component = getClass(sf, 'TestCmp');
const extendedTemplateChecker = new ExtendedTemplateCheckerImpl(
templateTypeChecker, program.getTypeChecker(), [nullishCoalescingNotNullableFactory],
{} /* options */);
const diags = extendedTemplateChecker.getDiagnosticsForComponent(component);
expect(diags.length).toBe(0);
});

it('should not produce nullish coalescing warning for a type that includes undefined', () => {
const fileName = absoluteFrom('/main.ts');
const {program, templateTypeChecker} = setup([{
Expand Down Expand Up @@ -165,7 +201,7 @@ runInEachFileSystem(() => {
},
source: `
export class TestCmp {
func: (): string | null => null;
func = (): string | null => null;
}
`,
},
Expand Down

0 comments on commit 0778e6f

Please sign in to comment.