0

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

1
  • The parameter is optional. Why should there be an error when the parameter is missing? Commented Aug 5, 2022 at 7:25

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Try this way

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

2 Comments

In a TS Playground this also shows a compiler error for func2 getting called without arguments.
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.