Live streamJoin us for "State of code review 2024" on July 18thRegister today

TypeScript types

Kenny DuMez
Kenny DuMez
Graphite software engineer

TypeScript is a superset of JavaScript that adds static types. This addition helps catch errors during development, improving maintainability and making the codebase easier to understand at a glance. Understanding TypeScript types is crucial for developing robust applications. Here's an in-depth guide focusing on TypeScript types, their application, and how they improve the overall development experience.

TypeScript typed variables: TypeScript allows you to specify a type for variables using a simple syntax. Here are the basic types:

  1. Boolean: Represents a logical value, true or false.

    Terminal
    let isCompleted: boolean = false
  2. Number: All numbers in TypeScript are floating point values. These types can represent both integers and floats.

    Terminal
    let decimal: number = 6
    let hex: number = 0xf00d
    let binary: number = 0b1010
    let octal: number = 0o744
  3. String: Represents a sequence of characters. TypeScript supports both double-quoted (") and single-quoted (') strings, as well as template strings, which can span multiple lines and have embedded expressions.

    Terminal
    let color: string = 'blue'
    let fullName: string = 'Bob Bobbington'
    let greeting: string = `Hello, my name is ${fullName}`
  4. Array: TypeScript allows you to define an array of elements of a specific type using one of two possible syntaxes.

    Terminal
    let list: number[] = [1, 2, 3]
    // or using a generic array type
    let anotherList: Array<number> = [1, 2, 3]
  5. Tuple: Tuple types allow you to express an array where the type of a fixed number of elements is known, but need not be the same.

    Terminal
    let person: [string, number] = ['Chris', 22]
  6. Enum: A way of giving more friendly names to sets of numeric values.

    Terminal
    enum Color {
    Red,
    Green,
    Blue
    }
    let c: Color = Color.Green
  7. Any: A fallback to the dynamic nature of JavaScript, allowing any type of value, with no specific type-checking applied.

    Terminal
    let notSure: any = 4
    notSure = 'maybe a string instead'
    notSure = false
  8. Void: Used on function return types to signify that the function does not return a value.

    Terminal
    function warnUser(): void {
    console.log('This is my warning message')
    }
  9. Null and undefined: In TypeScript, both null and undefined actually have their own types named null and undefined respectively.

    Terminal
    let u: undefined = undefined
    let n: null = null
  10. Never: Represents the type of values that never occur. For functions that throw an exception or never return, such as function throwing errors.

    Terminal
    function error(message: string): never {
    throw new Error(message)
    }
  11. Object: Represents any non-primitive type. Note that object type is different from Object or {} and only allows you to assign any non-primitive types.

    Terminal
    let obj: object = { x: 0, y: 0 }

TypeScript enables you to add types to each of the parameters and the return value of a function to ensure that the correct types are passed and returned.

Example:

Terminal
function add(x: number, y: number): number {
return x + y
}

This function clearly states that add takes two parameters, both of which are numbers, and also returns a number.

A union type allows a variable to be one of several types. The pipe (|) is used to separate each type.

Example:

Terminal
let multiType: number | string
multiType = 20 // valid
multiType = 'twenty' // valid

Intersection types allow you to combine multiple types into one. This is often used for combining multiple objects into one object.

Example:

Terminal
type Employee = {
name: string
startDate: Date
}
type Admin = {
name: string
privileges: string[]
}
type ElevatedEmployee = Employee & Admin
let newEmployee: ElevatedEmployee = {
name: 'Alice',
startDate: new Date(),
privileges: ['create-server', 'access-database']
}

Generics provide a way to create reusable components. A component can handle values of various types without being type-specific.

Example:

Terminal
function insertAtBeginning<T>(array: T[], value: T) {
return [value, ...array]
}
const demoArray = [1, 2, 3]
const updatedArray = insertAtBeginning(demoArray, -1) // [-1, 1, 2, 3]

Type assertions are like type casting in other languages but perform no special checking or restructuring of data.

Example:

Terminal
let someValue: any = 'this is a string'
let strLength: number = (someValue as string).length

Type guards allow you to narrow down the type of an object within a conditional block.

Example:

Terminal
function isNumber(x: any): x is number {
return typeof x === 'number'
}
function isString(x: any): x is string {
return typeof x === 'string'
}
function padLeft(value: string, padding: string | number) {
if (isNumber(padding)) {
return Array(padding + 1).join(' ') + value
}
if (isString(padding)) {
return padding + value
}
throw new Error(`Expected string or number, got '${padding}'.`)
}

TypeScript provides several utility types to facilitate common type transformations. These include Partial<T>, Readonly<T>, Pick<T, K>, Record<K, T>, and more.

Example:

Terminal
interface Todo {
title: string
description: string
}
function updateTodo(todo: Todo, fieldsToUpdate: Partial<Todo>) {
return { ...todo, ...fieldsToUpdate }
}
const todo1 = {
title: 'organize desk',
description: 'clear clutter'
}
const todo2 = updateTodo(todo1, {
description: 'throw out trash'
})

For further reading on TypeScript types, see the official TypeScript documentation.

Stay unblocked. Ship faster.
Experience the new developer workflow - create, review, and merge code continuously. Get started with one command.
Get started

Give your PR workflow
an upgrade today

Stack easier | Ship smaller | Review quicker

Or install our CLI.
Product Screenshot 1
Product Screenshot 2