Optional generic type

As of TypeScript 2.3, you can use generic parameter defaults.

private logData<T, S = {}>(operation: string, responseData: T, requestData?: S) {
  // your implementation here
}

TS Update 2020: Giving void will make the generic type optional.

type SomeType<T = void> = OtherType<T>;

The answer above where a default value as the object is given make it optional but still give value to it.


Example with default type value is {}:

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

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

const someFunction:FunctionType = (a) => {

}

someFunction({ name: "Siraj" });
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
// Expected 2 arguments, but got 1.(2554)

Playground Link


Example with default generic type value is void

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

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

const someFunction:FunctionType = (a) => {

}

someFunction({ name: "Siraj" })

This is a good read on making generics optional.

Optional generic type in Typescript

Playground Link