繁体   English   中英

在 Angular 2 中获取“类型错误中缺少属性 X”

[英]Getting "Property X is missing in type error" in Angular 2

得到

Property 'conf' is missing in type '{ text: string; label: string; }'.

从这个对象:

{
  //...
  digitalSkills: {
    skills: [
      {
        name: '...',
        tooltip: {
          text: '...',
          label: '...'
        }
      },
      {
        name: '...',
        tooltip: {
          text: '...',
          label: '...'
        }
      }
    ],
     //...
  }
  //...
}

从这个设置:

export interface TooltipConfig {
  text:string;
  label:string;
  conf?:string;
}

export class Tooltip implements TooltipConfig {
  text:string;
  label:string;
  conf:(any);

  constructor(c:TooltipConfig) {
    this.text = c.text;
    this.label = c.label;
    c.conf && (this.conf = c.conf);
  }
}

export interface Section {
  //...
  digitalSkills?:{
    skills?:{
      name:string,
      tooltip:Tooltip
    }
}

我的问题是我在其他类中以相同的方式声明可选参数,它们似乎工作得很好。 我不明白这里出了什么问题以及如何解决它。

注意:我不是通过将(可选?)参数添加为空字符串来轻松修复。 我想知道这是什么原因和一般原理。

尝试正确理解和学习 TypeScript。

您需要在Tooltip类中将conf属性设为可选。

export class Tooltip implements TooltipConfig {
  text:string;
  label:string;
  conf?:(any);

  constructor(c:TooltipConfig) {
    this.text = c.text;
    this.label = c.label;
    c.conf && (this.conf = c.conf);
  }
}

或者你需要使用TooltipConfig接口作为Section接口中tooltip属性的类型。

export interface Section {
  //...
  digitalSkills?:{
    skills?:{
      name:string,
      tooltip:TooltipConfig 
    }
}

或者您可以在对象创建中实例化 Tooltip 类:

{
  //...
  digitalSkills: {
    skills: [
      {
        name: '...',
        tooltip: new Tooltip({
          text: '...',
          label: '...'
        })
      },
      {
        name: '...',
        tooltip: new Tooltip({
          text: '...',
          label: '...'
        })
      }
    ],
     //...
  }
  //...
}

看看这个示例代码

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM