Open In App

How to Return a TypeScript Interface that Changes based on Function Inputs ?

Last Updated : 23 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In modern TypeScript development, creating adaptable interfaces that can dynamically adjust based on varying inputs is crucial for building flexible and maintainable codebases.

TypeScript offers powerful features such as conditional types and mapped types, which enable developers to achieve this level of flexibility.

There are several ways to return a typescript interface that changes based on the functional inputs which are as follows:

Using Conditional Types

Conditional types in TypeScript enable us to define the types based on conditions. This allows for the creation of interfaces that adapt to varying input parameters.

Syntax:

type DynamicInterface<T> = T extends string
? { text: string }
: T extends number
? { value: number }
: never;

Example: To create a type DynamicInterface that adapts based on the input type T. If T is a string, the interface includes a text property of type string. If T is a number, the interface includes a value property of type number.

Javascript




type DynamicInterface<T> = T extends string
    ? { text: string }
    : T extends number
    ? { value: number }
    : never;
 
const dynamicStringInterface:
    DynamicInterface<string> = { text: 'hello' };
console.log(dynamicStringInterface);
 
const dynamicNumberInterface:
    DynamicInterface<number> = { value: 42 };
console.log(dynamicNumberInterface);


Output

{ text: 'hello' }
{ value: 42 }

Using Mapped Types

Mapped types allow for the transformation of properties within types. They can be combined with conditional types to dynamically modify interfaces.

Syntax:

type EnsureString<T, K extends keyof T> = T & { [P in K]: string };

Example: To demonstrate a helper type EnsureString that ensures a specified property of an object that is of type string.

Javascript




type EnsureString<T, K extends keyof T> =
    T & { [P in K]: string };
 
interface MyInterface {
    property1?: string;
    property2?: string;
}
 
const obj: EnsureString<MyInterface, 'property1'> =
    { property1: 'value' };
console.log(obj);


Output

{ property1: 'value' }


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads