TypeScript: Define Type (interface)

By Xah Lee. Date: . Last updated: .

Define your own named type

you can define your own named type.

there are two ways, one is by defining a type alias and the other way is to define a interface.

Type alias

type TypeName = type

// define a named type. either a number or string
type NumOrStr  = number | string;
// define a named type. a object that represent coordinate of a point
type Point = {
  x: number;
  y: number;
};

Interface

interface TypeName = {properties_syntax}

almost always used for JavaScript objects.

// define a named type. a object that represent coordinate of a point
interface Point = {
  x: number;
  y: number;
};

What's the difference between “type” and “interface”

Type alias can be used as alt name for primitive types. Interface cannot.

Interface type spec can be extended later in a different place. It is designed mostly just for JavaScript objects.

For beginners, you can stick with just type alias.