Skip to main content

ReturnType and Parameters

Sometimes you don't control the types. You might be importing a function from a third-party library that doesn't export the types of its parameters or return values.

You can extract these types directly from the function itself using ReturnType and Parameters.

ReturnType

ReturnType<Type> extracts the return type of a function type.

import { createComplexState } from "some-external-library";

// We want to store the state, but the library didn't export the type!
// We can extract it by passing the typeof the function:
type State = ReturnType<typeof createComplexState>;

const initialState: State = createComplexState();

The key mental leap here is typeof. ReturnType expects a type, not a value. createComplexState is a runtime value (a function). We use typeof to get its type signature, and pass that to ReturnType.

Parameters

Parameters<Type> extracts the parameter types of a function type into a tuple (an array with fixed types and length).

function submitOrder(orderId: string, retryCount: number, force: boolean) {
// ...
}

// Extracts: [orderId: string, retryCount: number, force: boolean]
type SubmitParams = Parameters<typeof submitOrder>;

// Now we can use this tuple to type an array of arguments
const queuedArgs: SubmitParams = ["order-123", 3, false];

// And spread them into the function safely
submitOrder(...queuedArgs);

Indexed Access with Parameters

Because Parameters returns a tuple (array type), you can access individual parameter types using indexed access. This is incredibly useful for typing a wrapper function where you only want to pass along specific arguments.

// Extract just the type of the first argument (orderId)
type OrderIdParam = Parameters<typeof submitOrder>[0]; // string

Use typeof to bridge the gap between runtime values and the type system, allowing ReturnType and Parameters to extract types from functions you don't control.