Home > other >  How to define function type with optional parameter in Typescript?
How to define function type with optional parameter in Typescript?

Time:05-03

I have a function with optional parameters that I pass down to another component.

update = (flag: boolean = true): void => {
  // ...
}

In the component that I pass this down to, I have a field called updateFunc that I want to assign this function. What should be the type of this field?

What I Tried

If I define the field like the following, I cannot call it with a parameter.

updateFunc: () => void;

If I define the field like the following, I cannot call it without a parameter.

updateFunc: (flag: boolean) => void;

If I define the field like the following, I lose the type safety.

updateFunc: any;

CodePudding user response:

You can define this:

updateFunc: (flag?: boolean) => void;

then the default value will be assigned to the flag parameter when the referenced function (update) will be executed.

CodePudding user response:

You can use the question mark.

function hello(name?: string): void {
    if (name) {
        console.log(`Hi ${name}!`);
    } else {
        console.log(`I don't know your name :(`);
    }
}

hello('M. Azyoksul'); // Hi M. Azyoksul!
hello(); // I don't know your name :(

If you need a default value, you can use assignment

function hello(name: string = 'masked man'): void {
    if (name) {
        console.log(`Hi ${name}!`);
    } else {
        console.log(`I don't know your name :(`);
    }
}

hello('M. Azyoksul'); // Hi M. Azyoksul!
hello(); // Hi masked man!
  • Related