Explicit type annotations

So far TypeScript inferred a lot. You can also tell it the types. Edit a greeter so person is a string and date is a Date:

function greet(person: string, date: Date) {
  console.log(`Hello ${person}, today is ${date.toDateString()}!`);
}

Read the signature as: greet takes a person of type string, and a date of type Date.

TypeScript will catch bad calls:

greet("Maddison", Date());
// Error: Argument of type 'string' is not assignable to parameter of type 'Date'.

Why? In JavaScript, Date() returns a string. new Date() returns a Date object:

greet("Maddison", new Date()); // OK

Inference

You do not need an annotation on every variable. TypeScript often figures it out:

let msg = "hello there!";
// msg is inferred as string

Prefer skipping annotations when the inferred type is already correct.

Erased types

Compile the typed greet and look at the JavaScript. Type annotations are gone:

"use strict";
function greet(person, date) {
  console.log(
    "Hello ".concat(person, ", today is ").concat(date.toDateString(), "!"),
  );
}
greet("Maddison", new Date());

Type annotations are not part of JavaScript runtimes. The compiler strips them. Remember: type annotations never change runtime behavior : they only affect compile-time checking and tooling.

Strictness

TypeScript can be loose (easy migration) or strict (maximum safety). New projects should turn strictness on:

{
  "compilerOptions": {
    "strict": true
  }
}

"strict": true enables several flags at once. The two biggest:

noImplicitAny

When TypeScript cannot infer a type, it falls back to any : which turns off checking for that value. noImplicitAny makes those implicit anys an error, so you annotate or fix the inference.

strictNullChecks

Without this flag, null and undefined can sneak into almost any type. With it on, you must handle them explicitly (unions, checks, optional chaining). That prevents a huge class of runtime bugs.

Practice

function greet(person: string, date: Date) {
  console.log(`Hello ${person}, today is ${date.toDateString()}!`);
}

greet("Maddison", new Date());
  1. Remove the annotations and hover in the editor : what does TypeScript still know?
  2. Pass Date() instead of new Date() and read the error.
  3. Enable "strict": true in tsconfig.json and fix anything it reports.