Skip to main content

Types in TypeScript

3 min read

Older Article

This article was published 9 years ago. Some information may be outdated or no longer applicable.

One of the most valuable things about TypeScript is the ability to use types. JavaScript uses weak-typing (sometimes called dynamic typing), which means we’re not required to specify datatypes for variables.

TypeScript adds that ability. It’s still optional (TypeScript works without specifying data types), but using them gives us benefits that plain JavaScript can’t offer, like code validation in our IDE.

Datatypes

TypeScript supports a range of types: boolean, number, string, array, tuple, enum, void, null, undefined, never and any.

To specify a datatype, append the variable with a colon followed by the type: variable: datatype.

Primitive types

Let’s start with string.

let myName: string = 'John';

Once we’ve created the variable, we can only assign strings to it. Attempting to assign a number or any other datatype throws an error.

name = 'Dave';
name = 12; // Type '12' is not assignable to type 'string'

Even though we get a transpilation error, the corresponding JavaScript file still gets created when compiling. That’s the expected default behaviour because there’s no easy way to tell if the code works or doesn’t based purely on type errors from the compiler. If we want stricter control, we can set the noEmitOnError flag for tsc (or the corresponding tsconfig.json file), and the transpiled JavaScript file will only be created when the TypeScript code has no errors. Think of it as strict mode for the transpiler.

Defining strings, booleans and numbers (the primitive types) is dead simple. The number type also handles decimals, hexadecimals, binaries and octals.

let age: number = 39;
let hex: number = 0xd00a;
let isAdmin: boolean = false;

Object types

When working with arrays, type definitions can be done in two ways. Either use a basic data type followed by square brackets, or use the generic array type with the element datatype specified:

const numbers: number[] = [0, 1];
// or:
const numbers: Array<number> = [0, 1];
// for mixed types:

const myArray: any[] = [0, 'test'];
// or:
const myArray: Array<any> = [0, 'test'];

any

Notice the any keyword above. It’s useful when we want to describe the type of a variable where we don’t yet know the exact datatype, or when an array contains multiple data types.

Data types for functions

When creating functions, we can work with data types too. We can specify the data type of the parameters and also the return type:

function greet(name: string): string {
  return `Hello ${name}!`;
}

function add(n: number, m: number): number {
  return n + m;
}

function attack(weapon: string, damageValue: number): void {
  let maxHealth = 100;
  if (weapon === 'sword') {
    maxHealth -= damageValue;
  }
}

Notice the last function: since it doesn’t return anything, we’ve specified the return type as void.