The spread of gradual/optional typing

(written by lawrence krubner, however indented passages are often quotes). You can contact lawrence at:

Typesafe brings gradual/optional typing to Javascript:

Type annotations in TypeScript are lightweight ways to record the intended contract of the function or variable. In this case, we intend the greeter function to be called with a single string parameter. We can try changing the call greeter to pass an array instead:

function greeter(person: string) {
return “Hello, ” + person;

var user = [0, 1, 2];

document.body.innerHTML = greeter(user);

Open in Playground
Re-compiling, you’ll now see an error:

greeter.ts(7,26): Supplied parameters do not match any signature of call target
Similarly, try removing all the arguments to the greeter call. TypeScript will let you know that you have called this function with an unexpected number of parameters. In both cases, TypeScript can offer static analysis based on both the structure of your code, and the type annotations you provide.

Notice that although there were errors, the greeter.js file is still created. You can use TypeScript even if there are errors in your code. But in this case, TypeScript is warning that your code will likely not run as expected.

Let’s develop our sample further. Here we use an interface that describes objects that have a firstname and lastname field. In TypeScript, two types are compatible if their internal structure is compatible. This allows us to implement an interface just by having the shape the interface requires, without an explicit ‘implements’ clause.