1

I want to type a function that takes in something OR nothing in typescript. How do I do that?

I've tried:

interface TestFn {
    (props: any | void): string
}

const thing: TestFn = (props) => 'whoo';
thing('something'); // this line is fine
thing(); // this is not okay

1 Answer 1

2

You can use optional parameters:

interface TestFn {
    (props?: any): string       // <- parameters is marked as optional
}

const thing: TestFn = (props) => 'whoo';
thing('something'); // this line is fine
thing(); // this line is fine as well

Parameter props is marked with ?, which means that the parameter is optional. You can find more information about optional parameters in TypeScript documentation, section Optional and Default Parameters.

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

1 Comment

oh duh. I have optional parameters in my code too lol. thanks for the help. i'll accept the answer asap!

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.