Saturday, November 3, 2018

TypeScript - DataTypes - objects

After functions, objects are extremely important in JavaScript. Therefore, it makes it imperative to learn it in TypeScript. There are numerous different ways of creating objects in TypeScript.

Let me create a new object holding a city data:

// objects and types
let cityData = {
name: "Hyderabad",
state: "Telangana",
areaSqMiles: 650,
};


Now, what happens behind the scenes is that TypeScript infers the type of this variable (cityData) should have, It infers that the type should be an object with a name field - which is a string. And an state field, another string. Also, an areaSqMiles filed of type - number.

I can prove this, by reassigning the cityData to another object.

cityData = {};

If, I do this, I get an error:

$ tsc getCity.ts
getCity.ts:37:1 - error TS2322: Type '{}' is not assignable to type '{ name: string; state: string; areaSqMiles: number; }'.
  Property 'name' is missing in type '{}'.

37 cityData = {};
   ~~~~~~~~



So, this whole object is turned into a type here. And here, it is also important to note. The name of the properties are also important. So, if I create a new object here.  In a function, the order of the input parameter types are important. Whereas, in a object the order is not important, as the order might change.

Now, I can be explicit about it. We can assign the types in object as:

// objects and types
let cityData: {name:string, state:string, areaSqMiles:number};

cityData = {
name: "Hyderabad",
state: "Telangana",
areaSqMiles: 650,
};

Now, if I compile this:

$ tsc getCity.ts
$

there is no error.

We can also write it as:

// objects and types
let cityData: {name:string, state:string, areaSqMiles:number} = {
name: "Hyderabad",
state: "Telangana",
areaSqMiles: 650,
};

$ tsc getCity.ts
$

Again, there is no error.  This is because the object created satisfies the definition.

No comments:

Post a Comment