2

I'm converting a component library over to Angular 12, and the linting is giving me errors on annotated properties like this one that will be initialized by the annotation:

@ViewChild(MatSort, { static: false }) sort: MatSort;

The error is:

(property) DataTableComponent.sort: MatSort Property 'sort' has no initializer and is not definitely assigned in the constructor.ts(2564)

I'm also getting other strange errors. For example:

  dataSource: MatTableDataSource<any> = new MatTableDataSource([])

Generates the following error:

Type 'MatTableDataSource' is not assignable to type 'MatTableDataSource'. Types of property 'sortingDataAccessor' are incompatible. Type '(data: never, sortHeaderId: string) => string | number' is not assignable to type '(data: any, sortHeaderId: string) => string | number'. Types of parameters 'data' and 'data' are incompatible. Type 'any' is not assignable to type 'never'.ts(2322)

Thoughts?

Ole
  • 41,793
  • 59
  • 191
  • 359

1 Answers1

4

Angular 12 by default will enables strict mode in TypeScript. The strict flag enables a wide range of type checking behavior like strictNullChecks,strictPropertyInitialization.

We can prevent the type checker from throwing an error with Angular's non-null assertion operator, !

@ViewChild(MatSort, { static: false }) sort!: MatSort;

Since strickNullChecks are enabled, empty array are infered as never[] , so our MatTableDataSource return never[] instead any[]

MatTableDataSource<never>(initialData?: never[] | undefined): never[]

we can fix this by adding any to MatTableDataSource

dataSource: MatTableDataSource<any> = new MatTableDataSource<any>([])
Chellappan வ
  • 23,645
  • 3
  • 29
  • 60