Home > Blockchain >  Typescript: Type a function with optional parameter
Typescript: Type a function with optional parameter

Time:08-05

I am looking for typing functions with optional argument

I tried this :

type MyFunctionType<T = null> = (options: T) => unknown;
const func1: MyFunctionType<{ option1: number }> = (options) => options.option1;
const func2: MyFunctionType = () => 'test';
console.log(func1({option1: 12})); // Ok
console.log(func2()); // Error : Expected 1 argument

typescript shows an error on func2.


So i tried with "?" on options parameter:

type MyFunctionType2<T = null> = (options?: T) => unknown;
const func1: MyFunctionType2<{ option1: number }> =  (options) => options.option1;
const func2: MyFunctionType2 = () => 'test';
console.log(func2()); // Ok
console.log(func1()); // No error is raised

But in this case, typescript does not show error for using func1 without parameter.

Is there a way to solve this ?

Thank you for reading

CodePudding user response:

Yes, using conditional types:

type MyFunctionType<T = null> = T extends null | undefined
    ? (options?: T) => unknown
    : (options: T) => unknown;

const func1: MyFunctionType<{ option1: number }> = (options) => options.option1;
const func2: MyFunctionType = () => 'test';

func2();
func1(); // shows an error "Expected 1 arguments, but got 0."

This defined the generic type MyFunctionType to be a function whose parameter is optional in case the type of the parameter is null, undefined or the union of both. You could even leave them out entirely in this case:

type MyFunctionType<T = null> = T extends null | undefined
    ? () => unknown
    : (options: T) => unknown;

Arguably though, I cannot really see a usecase for a type definition like this as it will always shadow the actual return type and force a single parameter while not allowing multiple ones which might help readability.

CodePudding user response:

Try this way type MyFunctionType<T = never> = (options: T) => unknown;

  • Related