Skip to content

Types

  • Boolean
  • Number
  • String
let firstName: string = "Matt";
let firstName = "Matt";

In some cases, type can be inferred from the value.

Disables type checking. Unsafe.

let x = true;
x = "string"; // Error: Type 'string' is not assignable
// to type 'boolean'.
Math.round(x); // Error: Argument of type 'boolean' is
// not assignable to parameter of type 'number'.

// Now with any
let y: any = true;
y = "string"; // no error; can be "any" type
Math.round(y); // no error; can be "any" type

Safer than any. You can assign anything to it, but you must narrow the type before using it.

let data: unknown = fetchFromAPI();

// Can't use it directly
data.toUpperCase(); // Error: Object is of type 'unknown'

// Must check the type first
if (typeof data === "string") {
  console.log(data.toUpperCase()); // Works!
}

Forces an error.

let a: never = false; // Error: Type 'boolean' is not
// assignable to type 'never'.

Primitives in JS, but also types in TS.

let b: undefined = undefined;
let c: null = null;

strictNullChecks must be enabled in tsconfig.json