Optional generic type in Typescript

Optional generic type in Typescript


Generic types are amazing to increase the flexibility of a function or class or an interface in Typescript. But at the same time, it also restricts. Here in this article, I will walk you through, how you can generic types optional in TypeScript.

Quick Solutions: Make generic type optional

Giving void to the generic type as default value makes that type optional. Wondering how? Check out the codes below.

function fetchData <T = void> ( url: string): T {
        const response:T = fetch(url);
        return response 

Now you can pass the fetchData either passing generic type or without it. 

interface User {
    id: string;
    name: string;

// Functin call with passing generic type

// Functin call without passing generic type

Detailed Example of optional generic type 

Following is a more detailed example in the typescript of how generic type can be made.

type BaseFunctionType<T1, T2> = (a:T1, b:T2) => void;

type FunctionType<T = void> = BaseFunctionType<{name: string}, T>

const someFunction:FunctionType = (a) => {


someFunction({ name: "Siraj" })

Method 2: With function overloading

This method is not much of use, as it only works on functions mainly. See the codes below.

class Logger {

        // Declarations
        private logData<T>(operation: string, responseData: T):T
        private logData<T, S>(operation: string, responseData: T, requestData?: S):T

        // Definition
        private logData<T, S>(operation: string, responseData: T, requestData?: S) {
            // ...body

If that doesn't fit your case, don't worry, the quick solution is universal and works in any case.

Frequently asked questions.

What are generics in TypeScript?

Generic is a feature in the language TypeScript to make the module (interface, function etc.) more generic. But does it do it? Suppose you call a function that returns something, but the type of the return changes on the basis of the type in the parameter, so it changes on every call to call. So it is not possible to hardcode a type in the function return type, so what would we do in that case? use `any`? No! Giving any to the return type doesn't contain any info about the type. So the returned value from the function is always unknown, so it is not actually dependent on the type of function parameter.


© 2020 Garbage Valuegarbage value logo