Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript Error: Property '0' is missing in type

I have my interface like this

export interface Details {
  Name: [{
    First: string;
    Last: string;
  }];
}   

I have an observable config variable:

Configuration: KnockoutObservable<Details> = ko.observable<Details>();

and I would like to assign it a value in the constructor as follows:

config = {
  Name: [{
    First: "ABC",
    Last: "DEF"
  },
  {
    First: "LMN",
    Last: "XYZ"
  }]
};

this.Configuration(config);

and I am getting an error:

Types of property 'Name' is incompatible and property '0' is missing in type.
Type '{ First:string; Last:string; }[]' is not assignable to 
type '[{ First: string; Last:string; }]'

I don't have control on changing the interface as it is being used elsewhere.
What is the correct way to initialize this config variable ?

Thanks in advance.

like image 332
rkt Avatar asked Jun 09 '17 01:06

rkt


People also ask

Is missing in type but required in type TypeScript?

The TypeScript error "Property is missing in type but required in type" occurs when we do not set all of the properties an object of the specified type requires. To solve the error, make sure to set all of the required properties on the object or mark the properties as optional.

Is missing the following properties from type?

The error "Type is missing the following properties from type" occurs when the type we assign to a variable is missing some of the properties the actual type of the variable expects. To solve the error, make sure to specify all of the required properties on the object.

Does not exist on type TypeScript?

The "Property does not exist on type '{}'" error occurs when we try to access or set a property that is not contained in the object's type. To solve the error, type the object properties explicitly or use a type with variable key names. Copied!

Is not assignable to type TypeScript?

The "Type 'string' is not assignable to type" TypeScript error occurs when we try to assign a value of type string to something that expects a different type, e.g. a more specific string literal type or an enum. To solve the error use a const or a type assertion.


2 Answers

I came across the same issue and got around it by changing the interface to:

    interface Details {
        Name: {
            First: string;
            Last: string;
        }[];
    }

I know you may not want the interface changed but hope this helps for anyone that is in this situation.

like image 151
RyanA91 Avatar answered Oct 17 '22 21:10

RyanA91


This error can come from incorrectly typing an array (like I just did):

myArray:[]; //Incorrect, results in error message of `Property '0' is missing in type`

myArray: Array<string>; //Correct

myArray: string[]; //Also correct

The reason is that brackets denote a tuple in Typescript, not an array.

The Docs

like image 38
Greg Gum Avatar answered Oct 17 '22 21:10

Greg Gum