Sunday, October 28, 2018

TypeScript - DataTypes - Types in Function Arguments

Functions can take advantage of types. Consider the function:

let myCity:string = "Hyderabad";

function getCity(){
return myCity;
}

console.log("getCity() == "+getCity());


Console Output:
getCity.js:5 getCity() == Hyderabad

Now, we modify the function such that we make the datatype of the return type explicit:

let myCity:string = "Hyderabad";

function getCity():string{
return myCity;
}

console.log("getCity() == "+getCity());

Now, I do get the same output at the console.

Console Output:
getCity.js:5 getCity() == Hyderabad

But, now if change the return value to return a number.

let myCity:string = "Hyderabad";

function getCity():string{
return 34;
}

console.log("getCity() == "+getCity());

I receive a compilation error:
getCity.ts:4:5 - error TS2322: Type '34' is not assignable to type 'string'.

This i because TypeScript will not allow the program to compile with a wrong return type.

void - using it as a return type:

//void type
function greet():void{
console.log("Greetings! Welcome to getCity.ts");
}

greet();

Console Output:
getCity.js:3 Greetings! Welcome to getCity.ts

But, it will give me an error when I try to return using this function:
getCity.ts:4:5 - error TS2322: Type '1234' is not assignable to type 'void'.

It is good to know what a function returns. But, many times the functions will have arguments and we will want a way to tell the types of the arguments being accepted by the function.

functions with types:
functions can be associated with type information with its:

  • arguments
  • return type


Consider the following example in TypeScript:
// function add to check for datatypes of arguments
function add(input1:number,input2:number):number{
var myResult = input1 + input2;
return myResult;
}

console.log("add(4,5) == "+add(4,5));

Console Output:
getCity.js:6 add(4,5) == 9

Now, if i change the last line of the above code snippet to:
console.log("add(4,5) == "+add(4,"5"));

Typescript issues the following compilation error:
$ tsc getCity.ts
getCity.ts:7:34 - error TS2345: Argument of type '"5"' is not assignable to parameter of type 'number'.

We can see that TypeScript protects me from accidentally passing a string input to to a add function.


Reference:



No comments:

Post a Comment