Types in TypeScript

This post is 4 years old. (Or older!) Code samples may not work, screenshots may be missing and links could be broken. Although some of the content may be relevant please take it with a pinch of salt.

One of the most important things with TypeScript in my opinion is the ability to use types. JavaScript uses weak-typing (sometimes also referred to as dynamic typing) which means that, as opposed to other programming languages, we are not required to specify the datatypes for variables that we are creating.

TypeScript adds this ability – it's still optional, TypeScript works without specifying data types but using them will provide us with certain benefits that are not otherwise available with JavaScript such as code validation in our IDE.

Datatypes

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

In order to specify any of these datatypes we need to append the variable with the colon character followed by the data type value: variable: datatype.

Primitive types

The first datatype we are going to take a look at is ‘string'.

let myName: string = 'John';

Once we have created the variable we can only assign strings to it. If we attempt to assign a number or any other datatype we'll get an error thrown.

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

Please note that even though we get a transpilation error the corresponding JavaScript file gets created when compiling our code. This is the expected, default behaviour because there's no easy way to tell if the code works or doesn't relying purely on type errors by the compiler. However, if we want we can specify the noEmitOnError flag for tsc (or the corresponding tsconfig.json file) and the transpiled JavaScript file will only be created if the TypeScript code has no errors. You can think of this as strict checks for the transpiler.

It's really straight-forward to define strings, boolean values as well as numbers (These are the types that we also refer to as primitive types). The number type allows for decimals, hexadecimals, binaries and octals as well.

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 – we can either use a basic data type followed by the square bracket notation or we can also use the generic array type, specifying the datatype of elements inside the array:

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 how in the above example we are also using the `any' keyword – this is really useful when we want to describe the type of a variable where we don't yet know the exact datatype or in situations where an array contains multiple data types.

Data types for functions

When creating functions, we can also work with data types and Interestingly enough we can not only specify the data type of the parameters that we wish to utilise in the function but 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 that in the case of the last function, where we are not returning anything, we have specified the return type to be void.