MediumJavaScriptTypeScript

Conditional Types & Infer

TypeScriptConditional TypesTypes

TypeScript's infer keyword lets you extract a type from within a conditional type expression — one of the most powerful features in the type system.

// Extract the return type of any function:
type MyReturnType<T> = T extends (...args: any[]) => infer R ? R : never;

// Extract the element type of an array:
type Unpack<T> = T extends (infer E)[] ? E : T;

// Unwrap a Promise:
type MyAwaited<T> = T extends Promise<infer V> ? V : T;

Your Task

Implement three runtime utilities that mirror the same logic at the value level:

FunctionBehaviour
getReturnType(fn)Calls fn() and returns its result
unwrapArray(val)Returns val[0] if val is an array, else val
unwrapPromise(val)Awaits val if it is thenable, else returns val

The TypeScript signatures use infer-style generics to keep full type inference.

Sample tests

Test #1unwrapArray extracts first element
Input: ["unwrapArray",[1,2,3]]
Output: 1
Test #2unwrapArray passes through non-array
Input: ["unwrapArray","not-an-array"]
Output: "not-an-array"
Test #3unwrapPromise passes through plain value
Input: ["unwrapPromise","plain-value"]
Output: "plain-value"