TypeScript Styleguide

Generic Constructors: Type vs Constructor Parameters

Two ways to specify generic parameters for constructors in TypeScript. Explore whether generics belong on the type annotation or the constructor call.

95%

Use Constructor Generics

5%

Use Type Annotation Generics

Constructor Generics

Specifying generic parameters directly on the constructor call.

Code Example

example.ts (constructor generic)
const map = new Map<string, number>();
const set = new Set<User>();
const promise = new Promise<Data>((resolve) => {
  resolve(data);
});

const regex = new RegExp<string>(/pattern/);

Key Benefits

  • Generics specified at call site
  • Clear where type parameters come from
  • Works naturally with constructors
  • Explicit type inference point
  • Commonly used in popular libraries
  • More control over type resolution

Statistics

Type Annotation Generics

Specifying generic parameters on the variable type annotation.

Code Example

example.ts (type annotation generic)
const map: Map<string, number> = new Map();
const set: Set<User> = new Set();
const promise: Promise<Data> = new Promise((resolve) => {
  resolve(data);
});

const regex: RegExp = new RegExp(/pattern/);

Key Benefits

  • Type declared separately from constructor
  • Better for readability in some cases
  • Separates type concerns
  • Can rely on type inference
  • More formal type annotation style
  • Works well when type is on line above

Statistics

Additional Insights

More data points to help you make an informed decision for your team.

995

repositories analyzed