Saturday, November 3, 2018

TypeScript - DataTypes - or (union) operator to include multiple types

Consider a case, where we would like the variable to be of type number or a string only. In this, case we would think that we can accomplish this by using the type any.

Using any we would have accomplished it as:
let cityElevation:any = 505;
cityElevation = "Five Hundred and Five meters";

Now, the problem with this, cityElevation could also be mentioned as false.

let cityElevation:any = false;
cityElevation = "Five Hundred and Five meters";

But, we do not want it like that. So, to address this problem, we have the union type whereby, we can use the or operator to include the desired types:

let cityElevation:string | number = 505;
cityElevation = "Five Hundred and Five meters";

In this, we are explicit in terms of the type allowed for the variable cityElevation. So, this works.

But, we try to cityElevation to a boolean value, the compilation fails:

let cityElevation:string | number = 505;
cityElevation = "Five Hundred and Five meters";
cityElevation = false;

$ tsc getCity.ts
getCity.ts:63:3 - error TS2322: Type 'false' is not assignable to type 'string | number'.

63   cityElevation = false;
     ~~~~~~~~~~~~~




No comments:

Post a Comment