Angular 12 中组件属性的初始化?
Initialization of component properties in Angular 12?
我正在将一个组件库转换为 Angular 12,linting 在注释属性上给我错误,就像这个将由注释初始化的属性:
@ViewChild(MatSort, { static: false }) sort: MatSort;
错误是:
(property) DataTableComponent.sort: MatSort
Property 'sort' has no initializer and is not definitely assigned in the constructor.ts(2564)
我还收到其他奇怪的错误。例如:
dataSource: MatTableDataSource<any> = new MatTableDataSource([])
生成以下错误:
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)
想法?
Angular 默认情况下,12 将在 TypeScript 中启用严格模式。 strict 标志启用了广泛的类型检查行为,例如 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;
由于启用了 strickNullChecks,空数组被推断为 never[] ,所以我们的 MatTableDataSource return never[] 而不是 any[]
MatTableDataSource<never>(initialData?: never[] | undefined): never[]
我们可以通过向 MatTableDataSource 添加 any 来解决这个问题
dataSource: MatTableDataSource<any> = new MatTableDataSource<any>([])
我正在将一个组件库转换为 Angular 12,linting 在注释属性上给我错误,就像这个将由注释初始化的属性:
@ViewChild(MatSort, { static: false }) sort: MatSort;
错误是:
(property) DataTableComponent.sort: MatSort Property 'sort' has no initializer and is not definitely assigned in the constructor.ts(2564)
我还收到其他奇怪的错误。例如:
dataSource: MatTableDataSource<any> = new MatTableDataSource([])
生成以下错误:
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)
想法?
Angular 默认情况下,12 将在 TypeScript 中启用严格模式。 strict 标志启用了广泛的类型检查行为,例如 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;
由于启用了 strickNullChecks,空数组被推断为 never[] ,所以我们的 MatTableDataSource return never[] 而不是 any[]
MatTableDataSource<never>(initialData?: never[] | undefined): never[]
我们可以通过向 MatTableDataSource 添加 any 来解决这个问题
dataSource: MatTableDataSource<any> = new MatTableDataSource<any>([])