TS2339错误:Object类型无type属性的非接口解决方案咨询
不用接口解决TypeScript模板属性访问错误的几种方案
给你几个不用创建接口的解决办法:
方法1:将数组类型改为any[]
修改Card类里的类型定义,把Object[]替换成any[],这样TypeScript会跳过对数组元素的严格类型检查,模板里访问phone.type就不会报错:
export class Card { private _phones: any[] get phones(): any[]{ if(this._phones === undefined) this._phones = [] return this._phones } set phones(val: any[]){ this._phones = val } }
注意:使用any会完全失去类型校验,后续如果属性名拼写错误,编译时不会给出提示,需要自己留意。
方法2:在模板中用$any()绕过类型检查
不用修改Card类的定义,直接在HTML模板里使用Angular提供的$any()语法,临时将phone断言为任意类型:
<ng-container *ngFor="let phone of card.phones"> <ng-container *ngIf="$any(phone).type === 'personal'"> <div fxLayout="row" fxFlex="100%"> <!-- 你的内容 --> </div> </ng-container> </ng-container>
这种方式无需改动原有类结构,仅在模板层面绕过类型检查,适合不想修改类型定义的场景。
方法3:用索引签名类型+模板内类型断言
如果不想用any,可以把Card类里的类型改成Record<string, unknown>[],再在模板里做针对性的类型断言:
先修改Card类:
export class Card { private _phones: Record<string, unknown>[] get phones(): Record<string, unknown>[]{ if(this._phones === undefined) this._phones = [] return this._phones } set phones(val: Record<string, unknown>[]){ this._phones = val } }
然后模板中这样写:
<ng-container *ngFor="let phone of card.phones"> <ng-container *ngIf="(phone as { type: string }).type === 'personal'"> <div fxLayout="row" fxFlex="100%"> <!-- 你的内容 --> </div> </ng-container> </ng-container>
这种方式比any保留了部分类型约束,同时不需要创建单独的接口。
内容的提问来源于stack exchange,提问作者Moblize IT
相关产品推荐
相关产品推荐

