“typescript TS2339: Property ‘phoneType’ does not exist on type ‘Object'”

huangapple go评论68阅读模式
英文:

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&lt;T extends HasTypeProperty&gt; {
  private _phones: T[];
      ....
}

huangapple
  • 本文由 发表于 2023年5月22日 11:32:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76302885.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定