英文:
typescript TS2339: Property 'phoneType' does not exist on type 'Object'
问题
我有一个对象声明如下:
export class Card {
private _phones: Object[]
get phones(): Object[]{
if(this._phones === undefined)
this._phones = []
return this._phones
}
set phones(val: Object[]){
this._phones = val
}
}
在我的HTML某处,我的代码如下:
<ng-container *ngFor="let phone of card.phones">
<ng-container *ngIf="phone.type === 'personal'">
<div fxLayout="row" fxFlex="100%">
上述代码引发了编译错误:
Error: src/app/process-card/process-card.component.html:128:46 - error TS2339: Property 'type' does not exist on type 'Object'.
128 <ng-container *ngIf="phone.type === 'personal'">
我理解我的卡片类型是Object,不能确定phone.type。然而,除了创建一个接口来绕过此问题之外,是否有其他解决方法?
英文:
I have an object declared as below:
export class Card {
private _phones:Object[]
get phones(): Object[]{
if(this._phones === undefined)
this._phones = []
return this._phones
}
set phones(val:Object[]){
this._phones = val
}
}
somewhere in my html my code looks like
<ng-container *ngFor="let phone of card.phones">
<ng-container *ngIf="phone.type === 'personal'">
<div fxLayout="row" fxFlex="100%">
The above code throws the compilation error:
Error: src/app/process-card/process-card.component.html:128:46 - error TS2339: Property 'type' does not exist on type 'Object'.
128 <ng-container *ngIf="phone.type === 'personal'">
I do understand the issue that my card type is of object and phone.type cannot be determined. However, instead of creating an interface to bypass this is there any other workaround?
答案1
得分: 1
尽量避免在你的代码中使用 'any'。以下是几种可能的解决方案:
interface PhoneInterface {
type: string;
}
export class Card {
private _phones: PhoneInterface[];
// 其他代码...
}
或者:
interface HasTypeProperty {
type: string;
}
export class Card<T extends HasTypeProperty> {
private _phones: T[];
// 其他代码...
}
英文:
Try to avoid 'any' in your code. Couple of possible solutions is below:
interface PhoneInterface {
type: string;
}
export class Card {
private _phones: PhoneInterface[]
....
}
Or:
interface HasTypeProperty {
type: string;
}
export class Card<T extends HasTypeProperty> {
private _phones: T[];
....
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论