TypeScriptInterfaces and classes
type
A type alias: a name for any type, including unions, tuples, and complex types.
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 = typeGood 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 throughtype.
Related entries
#- interface vs typeinterface describes an object’s shape and can be extended or merged with another declaration of the same name, while type aliases any type, including unions and tuples.
- interfaceA named description of an object’s shape that you can extend and merge.
- Literal typesTypes that allow only specific values, e.g. "easy" | "hard".
Spotted a mistake or missing an example? Write to us.