bugl
bugl
HomeLearnPatternsPathsSearchPremium
HomeLearnPatternsPaths
Learn/TypeScript/TypeScript Core
TypeScript•TypeScript Core

TypeScript Basic Generics

Generics allow creating 'type variables' which can be used to create classes, functions & type aliases that don't need to explicitly define the types that they use.

Generics make it easier to write reusable code.

Functions

Generics with functions help create more general functions that accurately represent the input and return types.

Example

function createPair<S, T>(v1: S, v2: T): [S, T] {
  return [v1, v2];
}
console.log(createPair<string, number>('hello', 42)); // ['hello', 42]

TypeScript can also infer the type of the generic parameter from the function parameters.

Classes

Generics can be used to create generalized classes, like Map .

Example

class NamedValue<T> {
  private _value: T | undefined;
  constructor(private name: string) {}
  public setValue(value: T) {
    this._value = value;
  }
public getValue(): T | undefined {
  return this._value;
}
public toString(): string {
  return `${this.name}: ${this._value}`;
}
}
let value = new NamedValue<number>('myNumber');
value.setValue(10);
console.log(value.toString()); // myNumber: 10

TypeScript can also infer the type of the generic parameter if it's used in a constructor parameter.

Type Aliases

Generics in type aliases allow creating types that are more reusable.

Example

type Wrapped<T> = { value: T };
const wrappedValue: Wrapped<number> = { value: 10 };

This also works with interfaces with the following syntax: interface Wrapped<T> {

Default Value

Generics can be assigned default values which apply if no other value is specified or inferred.

Example

class NamedValue<T = string> {
 private _value: T | undefined;
 constructor(private name: string) {}
 public setValue(value: T) {
 this._value = value;
 }
 public getValue(): T | undefined {
 return this._value;
 }
 public toString(): string {
 return `${this.name}: ${this._value}`;
 }
}
let value = new NamedValue('myNumber');
value.setValue('myValue');
console.log(value.toString()); // myNumber: myValue

Extends

Constraints can be added to generics to limit what's allowed.

The constraints make it possible to rely on a more specific type when using the generic type.

Example

function createLoggedPair<S extends string | number, T extends string | number>(v1: S, v2: T): [S, T] {
 console.log(`creating pair: v1='${v1}', v2='${v2}'`);
 return [v1, v2];
}

This can be combined with a default value.

Previous

TypeScript Classes

Next

TypeScript Utility Types

This chapter

Overview
40

Lessons

241m

Read time

1. TypeScript Tutorial2. TypeScript Introduction3. TypeScript Getting Started4. TypeScript Simple Types5. TypeScript Explicit Types and Inference6. TypeScript Special Types7. TypeScript Arrays8. TypeScript Tuples9. TypeScript Object Types10. TypeScript Enums11. TypeScript Type Aliases and Interfaces12. TypeScript Union Types13. TypeScript Functions14. TypeScript Casting15. TypeScript Classes16. TypeScript Basic Generics17. TypeScript Utility Types18. TypeScript Keyof19. TypeScript Null & Undefined20. TypeScript Definitely Typed21. TypeScript 5.x Updates22. TypeScript Configuration23. TypeScript with Node.js24. TypeScript with React25. TypeScript Tooling26. TypeScript Advanced Types27. TypeScript Type Guards28. TypeScript Conditional Types29. TypeScript Mapped Types30. TypeScript Type Inference31. TypeScript Literal Types32. TypeScript Namespaces33. TypeScript Index Signatures34. TypeScript Declaration Merging35. TypeScript Async Programming36. TypeScript Decorators37. TypeScript in JavaScript Projects (JSDoc)38. TypeScript Migration Guide39. TypeScript Error Handling40. TypeScript Best Practices

On this page

FunctionsClassesType AliasesDefault ValueExtends