Open In App

How to Restrict a Generic Interface from Accepting an Unknown Data Type ?

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

Restricting a generic interface from accepting an unknown data type means specifying constraints on the type parameter to disallow the unknown. This ensures that the interface can only be instantiated with types that are more specific than unknown, enhancing type safety and preventing unintended usage of potentially unsafe data types.

Below are the approaches used to restrict a generic interface from accepting an unknown data type:

Approach 1: Using conditional types

Using conditional types in TypeScript involves creating type definitions that depend on the evaluation of type conditions, enabling conditional logic to determine the resulting type based on specific type constraints and conditions.

Syntax:

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

Example: In this example we Defines NotUnknown<T> type to allow only string types, ensuring MyInterface’s data property holds strings.

Javascript




type NotUnknown<T> = T extends string ? T : never;
 
interface MyInterface<T> {
    data: NotUnknown<T>;
}
 
const result: MyInterface<string> = {
    data: "GeeksforGeeks"
};
 
console.log(result.data);


Output:

GeeksforGeeks

Approach 2: Using mapped types

Using mapped types in TypeScript involves transforming types by iterating over their properties and applying specified operations, enabling dynamic creation of new types based on existing ones.

Syntax:

type MyMappedType<T> = { [K in keyof T]: SomeType; }

Example: In this example we Defines a mapped type NotUnknown<T> excluding unknown, ensuring MyInterface’s data property holds only specified types. we use string and number both in our data.

Javascript




type NotUnknown<T> = {
    [K in keyof T]: T[K] extends unknown ? never : T[K]
};
 
interface MyInterface<T> {
    data: NotUnknown<T>;
}
 
const result1: MyInterface<number | string> = {
    data: 18
};
 
console.log(result1.data);
 
const result2: MyInterface<number | string> = {
    data: "Virat_Kohli"
};
 
console.log(result2.data);


Output:

18
Virat_Kohli


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads