type

A type alias: a name for any type, including unions, tuples, and complex types.

On this page

Example

#
TypeScript
type Difficulty = 'easy' | 'medium' | 'hard'
type Task = {
  title: string
  difficulty: Difficulty
  exp: number
}
type Handler = (task: Task) => string

const summary: Handler = (task) => `${task.title} (${task.difficulty}): +${task.exp} EXP`

console.log(summary({ title: 'Flexbox', difficulty: 'medium', exp: 20 }))
Result
Flexbox (medium): +20 EXP

Definition and usage

#

The type keyword creates an alias, meaning a new name for an existing type. It can be an object type, but also a union ("easy" | "hard"), a tuple, a function type, or the result of a utility type.

Aliases and interfaces work very similarly when describing objects. The differences: an alias can’t be “reopened” with a second declaration of the same name, and you extend it with the & intersection instead of extends.

Aliases are essential everywhere an interface isn’t enough: with unions, conditional types, mapped types, and template literal types.

Syntax

#
Syntax
type Name = type

Good practices

#
  • Always write unions, tuples, and function types with type. An interface can’t express them.
  • Settle on a simple rule as a team, for example: objects through interface, everything else through type.

Related entries

#

Spotted a mistake or missing an example? Write to us.