How to annotate simple types using TypeScript
Type annotations with TypeScript are simple decorators appended to the variable or function after a colon. There's support for the same primitive types as in JavaScript, and to declare interfaces and classes, which we will discuss next.
How to do it…
Here's a simple example of some variable declarations and two function declarations:
function greeter(person: string): string { return "Hello, " + person; } function circumference(radius: number) : number { var pi: number = 3.141592654; return 2 * pi * radius; } var user: string = "Ray"; console.log(greeter(user)); console.log("You need " + circumference(2) + " meters of fence for your dog.");
This example shows how to annotate functions and variables.
How it works…
Variables—either standalone or as arguments to a function—are decorated using a colon and then the type. For example, the first function, greeter
, takes a single argument, person, which must be a string. The second function, circumference...