1

I am a newbie at TypeScript and after installing it successfully on my machine, I came across the sentence "Type annotations in TypeScript are lightweight ways to record the intended contract of the function or variable" in TypeScript's official documentation page.

What is the word contract explained in the context of a function or variable in TypeScript.

The example that I took a look at was:

function greeter(person: string){
   return "Hello, " + person;
}

var user = "Jane User";

document.body.innerHTML=greeter(user);

Is it something to do with string annotation attached with the function variable person?

Any help on this is appreciated.

Here is the link to the official documentation

Aditya
  • 1,172
  • 11
  • 32

2 Answers2

2

If you are interested in the word contract in this context: just as you can expect your employer to pay your salary at the end of each month according to your contract, you can expect that the argument of greeter will be a string (however you can break this contract very easily)

Balázs Édes
  • 13,452
  • 6
  • 54
  • 89
1

I will try to explain, using example. Here is the code:

function greeter(person: string){
   return "Hello, " + person;
}

var user = "Jane User";

document.body.innerHTML=greeter(user);

we’ve gone from passing a string value into the greeter() function to passing a number value. True to JavaScript’s dynamic nature, it doesn’t care - it just goes ahead and converts it to a string in order to render it to the browser. TypeScript is also happy, since the number can be converted to a string.

Here’s the problem: that’s not what I intended to happen. I only ever intended for the greeter method to accept a string value, but JavaScript doesn’t let me express that intent. The only way I can ever guarantee that the parameter value is a string is to write code to check it at runtime in javascript.

Here’s where TypeScript "intended contract" plays. If I only ever want strings to be passed in, I can say so by explicitly saying that the value parameter is a string.