0
0
Typescriptprogramming~7 mins

Conditional types for overload replacement in Typescript

Choose your learning style9 modes available
Introduction

Conditional types let you choose a type based on a condition. This helps replace multiple function overloads with simpler code.

When you want one function to handle different input types and return matching output types.
When you want to avoid writing many overloads for similar functions.
When you want clearer and shorter type definitions that adapt automatically.
When you want to improve code readability by reducing repetition.
When you want TypeScript to infer return types based on input types.
Syntax
Typescript
type Result<T> = T extends Condition ? TrueType : FalseType;

The extends keyword here means 'if T fits Condition'.

The type after ? is used if true, after : if false.

Examples
This type returns "yes" if T is string, otherwise "no".
Typescript
type IsString<T> = T extends string ? "yes" : "no";
This extracts the type inside an array, or returns T if not an array.
Typescript
type ElementType<T> = T extends (infer U)[] ? U : T;
This function returns a string if input is number, else boolean, using conditional types.
Typescript
function example<T>(arg: T): T extends number ? string : boolean {
  return (typeof arg === "number" ? "number" : false) as any;
}
Sample Program

This program uses a conditional type to decide the return type of process. If the input is a number, it returns a string message. Otherwise, it returns false (a boolean).

Typescript
type ReturnType<T> = T extends number ? string : boolean;

function process<T>(value: T): ReturnType<T> {
  if (typeof value === "number") {
    return `Number is ${value}` as ReturnType<T>;
  } else {
    return false as ReturnType<T>;
  }
}

console.log(process(10));
console.log(process("hello"));
OutputSuccess
Important Notes

Conditional types work at compile time to help TypeScript understand your code better.

Use infer inside conditional types to extract types from complex structures.

Conditional types can replace many overloads but sometimes overloads are clearer for complex cases.

Summary

Conditional types choose a type based on a condition, like an if-else for types.

They help replace multiple function overloads with one flexible function.

This makes code shorter, easier to read, and types safer.