0

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;
2
  • 1
    Is it just updateFunc: (flag?: boolean) => void;? Commented May 2, 2022 at 23:30
  • @pzaenger This works in my testing. Should be an answer. Thank you. Commented May 2, 2022 at 23:47

2 Answers 2

4

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.

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

Comments

1

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!

Comments

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.