Angular 12 中组件属性的初始化? [英] Initialization of component properties in Angular 12?

查看:28
本文介绍了Angular 12 中组件属性的初始化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将一个组件库转换为 Angular 12,并且 linting 给了我关于注释属性的错误,比如这个将由注释初始化的属性:

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;

错误是:

(属性)DataTableComponent.sort:MatSort属性 'sort' 没有初始化器,也没有在构造函数中明确分配. ts(2564)

(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([])

产生以下错误:

类型MatTableDataSource"不可分配给类型MatTableDataSource".属性sortingDataAccessor"的类型不兼容.输入'(数据:从不,sortHeaderId:字符串)=>字符串 |number' 不可分配给类型 '(data: any, sortHeaderId: string) =>字符串 |数字'.参数data"和data"的类型不兼容.类型any"不可分配给类型never".ts(2322)

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 默认会在 打字稿.strict 标志启用了广泛的类型检查行为,例如 strictNullChecks、strictPropertyInitialization.

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

我们可以防止类型检查器在 Angular 的非空断言运算符,!

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 返回 never[] 而不是 any[]

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

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

我们可以通过添加任何到 MatTableDataSource 来解决这个问题

we can fix this by adding any to MatTableDataSource

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

这篇关于Angular 12 中组件属性的初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆