Andrei Gheorghiu Andrei Gheorghiu - 2 months ago 8
TypeScript Question

Getting "Property X is missing in type error" in Angular 2

Getting

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


from this object:

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


from this setup:

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
}
}


My problem is I declare optional parameters in other classes the same way and they seem to work just fine. I don't understand what's wrong here and how I can fix it.

Note: I'm not after an easy fix by adding the (optional?) parameter as an empty string. I would like to know the cause of this and the general principle.

Trying to understand and learn TypeScript properly.

Answer

You need to make the conf property optional in the Tooltip class.

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);
  }
}

Or you need to use the TooltipConfig interface as the type for the tooltip property in theSection interface.

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

Or you can instantiate the Tooltip class in the object creation:

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

Take a look at this sample code.