Rico Kahler Rico Kahler - 2 months ago 8
TypeScript Question

How do I type a function with parameters as `any` or `void` in typescript?

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

Answer

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.