Types in TypeScript

Ward Price
2 min readFeb 15, 2021

TypeScript allows us to write error proof code by specifying which type the variables we write are. This makes it easier for anyone new to the codebase you are working on to understand what data type is going where.

The most basic data types are

string
number
boolean
enum
void
null
undefined
any
never
array

String

String type is mean for a sequence of one or more characters that may consist of letters, numbers, or symbols.

Number

Javascript does not specify between different types of numbers (floats, short, long) besides bigInt. In JavaScript/TypeScript numbers are always stored as double floating point numbers.

Boolean

A boolean type is one that simply represents the value true or false.

Enum

Enums are a special feature of TypeScript that do not exist in JavaScript. Enums allow a developer to define a set of named constants.

For example:

enum PrimaryColorsOfLight {
red,
green,
blue
}

Void

Void type is also a TypeScript type. We use it to say ‘this function will not return anything’. A really simple example would be a function that does not return anything but instead logs a value to the console.

Null & undefined

Null and undefined are types you could assign to a number but really when you set your tsconfig.json to --strictNullChecks then you can only assign them to type unknown. They are best used with union types.

Say you have a variable that could at any time be null or benumber. You can create a union type by simply using the or | operator

const numberOrNull: number | null = 0

Any

The any type should really never be used except for during developement. By using any you are removing all the help that TypeScript provides. That being said, I find myself using it sometimes for function return types as I’m figuring out how I’m going to tackle a problem. Once solved I do go back and enter the right type so that in the future it doesn’t come back to bite me.

Never

This is a tricky one. I’ve used it for errors as they never reach an endpoint but instead throw an exception and that is what the type means, it is reserved for functions that never reach an endpoint.

Array

To let TypeScript know you are using an array all you have to do is specify the types in the array then give it an empty array.

const numArr: number[] = [1, 2]
const numArr2: Array<number> = [3, 4]

For multiple types you again can use an union type

const multiArray: (number | string) = [1, 'peach']
const multiArray2: Array<number | string> = [2, 'blackberry']

This is just a quick overlook at the most baisc types in Typescript and how to use them. Hopefully you found it helpful, happy coding!

--

--