๐ŸŽ“ A1Learner
๐Ÿ”
0 of 42 lessons completed

TypeScript Function Type Utilities

ReturnType, Parameters and InstanceType read types from a function or class that already exists. The source definition stays the single place where the shape is written.

ReturnType reads the result shape

ReturnType copies the return shape of a function into a named type. A second value can then use that shape without repeating it.

function createUser() {
  return { id: 7, userName: 'Ana', active: true };
}
type UserRecord = ReturnType<typeof createUser>;
const loaded: UserRecord = { id: 8, userName: 'Ben', active: false };
console.log(loaded.userName);
console.log(loaded.active);

Parameters types a logging wrapper

Parameters reads the argument tuple of the wrapped function. The wrapper spreads that tuple into the original call.

function sendAlert(channel: string, level: number): string {
  return channel + ' level ' + level;
}
type AlertArgs = Parameters<typeof sendAlert>;
function loggedSend(...args: AlertArgs): string {
  console.log('calling sendAlert');
  return sendAlert(...args);
}
console.log(loggedSend('email', 2));

InstanceType types a registry

InstanceType reads the instance shape from a class constructor. A registry can store instances without naming the class type by hand.

class Counter {
  constructor(public start: number) {}
  next(): number {
    this.start += 1;
    return this.start;
  }
}
type CounterInstance = InstanceType<typeof Counter>;
const registry: Record<string, CounterInstance> = {};
registry.main = new Counter(10);
console.log(registry.main.next());

Example

class Product {
  constructor(public sku: string, public price: number) {}
}
function loadProduct(sku: string, price: number): Product {
  return new Product(sku, price);
}
type LoadedProduct = ReturnType<typeof loadProduct>;
type LoadArgs = Parameters<typeof loadProduct>;
type ProductInstance = InstanceType<typeof Product>;
const args: LoadArgs = ['KB-1', 49];
const item: LoadedProduct = loadProduct(...args);
const spare: ProductInstance = new Product('KB-2', 59);
console.log(item.sku);
console.log(spare.price);

Key points

  • ReturnType<typeof fn> gives the type of the value that fn returns.
  • Parameters<typeof fn> gives a tuple type holding the parameter types of fn in order.
  • The typeof operator in a type position reads the type of a value without calling it.
  • InstanceType<typeof C> gives the type of instances built by the class constructor C.
  • The read types update on their own when the source function or class changes.

In this example, all three utilities read from definitions that already exist, so the tuple, the loaded product and the spare instance stay in step with the source code.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท TypeScript Playground

Exercise

What does Parameters<typeof fn> produce for a function fn?