Hone logo
Hone
Problems

TypeScript: Advanced Return Type Inference Helper

In TypeScript, inferring return types accurately is crucial for writing robust and maintainable code. Sometimes, defining complex return types manually can be verbose and error-prone. This challenge focuses on creating a utility type that can automatically infer and construct a desired return type from existing function types.

Problem Description

Your task is to create a TypeScript utility type named InferReturnType. This utility type should accept a function type as input and return a type that represents the return type of that function. This is a common pattern for building more advanced type manipulation utilities.

Key Requirements:

  1. The utility type InferReturnType<T> should be generic and accept one type parameter, T.
  2. T is expected to be a function type.
  3. The resulting type should be the return type of the function T.
  4. Handle cases where T is not a function type gracefully (though the primary focus is on function types).

Expected Behavior:

If T is a function type like (arg1: number, arg2: string) => boolean, InferReturnType<T> should resolve to boolean.

Edge Cases to Consider:

  • What happens if T is not a function type (e.g., a primitive type, an object, an array)? The most common approach is to have it resolve to never or unknown in such cases, indicating it's not a valid input for return type inference.

Examples

Example 1:

type MyFunction = (a: number, b: string) => boolean;

// InferReturnType<MyFunction> should resolve to 'boolean'

Example 2:

type AnotherFunction = () => { id: number; name: string };

// InferReturnType<AnotherFunction> should resolve to '{ id: number; name: string }'

Example 3:

type NotAFunction = string;

// InferReturnType<NotAFunction> should resolve to 'never' (or 'unknown')

Constraints

  • The solution must be a single TypeScript utility type.
  • No external libraries or npm packages are allowed.
  • The solution should be purely a type-level operation.

Notes

Think about how TypeScript allows you to extract parts of existing types. Conditional types and infer keywords are powerful tools for this kind of task. Consider the structure of a function type and how you might deconstruct it to get just the return part.

Loading editor...
typescript