Close

TypeScript - Generic Type Aliases

[Last Updated: Oct 28, 2018]

TypeScript allows to use generic type aliases. Let's see how to do that with an example.

Example

type ListType<T> = {elements:T[]};
let numList : ListType<number> = {elements: [1,2,3,4]};
console.log(numList);

Output

{ elements: [ 1, 2, 3, 4 ] }

Generic Type aliases can be used with intersection and union types as well:

type Entity<E> = { id: number } & E;

interface Item {
    name: string;
    price: number;
}

let itemEntity: Entity<Item> = {id: 1, name: "Laptop", price: 150};
console.log(itemEntity);

Output

{ id: 1, name: 'Laptop', price: 150 }

Example Project

Dependencies and Technologies Used:

  • TypeScript 3.1.3
Using generics in Type Aliases Select All Download
  • typescript-type-aliases-with-generics
    • type-alias-with-generics.ts

    See Also