Saturday, November 3, 2018

TypeScript - DataTypes - complex Object

Below, we have an example of a complex object defined in TypeScript:

// complex object
let myComplexObject:{dataArray:number[], outputFunc:(all:boolean) => number[]} ={
dataArray:[10,20,30,40,50],
outputFunc: function (all:boolean): number[] {
return this.dataArray;
}
}

This object is defined by the blueprint:
let myComplexObject:{dataArray:number[], outputFunc:(all:boolean) => number[]}

This blueprint tells that the object should be having:
a property: which is an array of numbers
a method: which returns an array of numbers and takes in a boolean argument.

Therefore, I can reassign this object as:

myComplexObject = {dataArray:[1,2,3,4,5],
outputFunc: function (all:boolean): number[] {
return this.dataArray;
}};

Now, I don't get an error on this reassignment. But, if I assign it to an empty object:

myComplexObject = {};

and try to compile it...

$ tsc getCity.ts
getCity.ts:51:5 - error TS2322: Type '{}' is not assignable to type '{ dataArray: number[]; outputFunc: (all: boolean) => number[]; }'.
  Property 'dataArray' is missing in type '{}'.

51     myComplexObject = {};
       ~~~~~~~~~~~~~~~




Now I get an error as above.


No comments:

Post a Comment