Dakito
Dakito

Reputation: 387

How to omit the optional function which is parameter

I have no problem with optional primitive parameters but with optional function. Lets say i have function which needs 1 required parameter and one optional

function doSomething(value: string, callback?: () => void){
let temp = value;
callback(); // callback!() also doesn't work
}

doSomething('test') // this line throws 'callback is not a function'

Upvotes: 0

Views: 133

Answers (3)

Karol Majewski
Karol Majewski

Reputation: 25800

The right way to do it is to check whether the callback was provided:

function doSomething(value: string, callback?: () => void){
    if (callback !== undefined) {
        callback();
    }
}

If that makes sense in your case, a default argument can be also used.

function doSomething(value: string, callback: () => void = () => {}){
    callback();
}

Upvotes: 2

Katya Pavlenko
Katya Pavlenko

Reputation: 3383

Try using this syntax:

let t = function (a, b = () => { console.log('default') }) {
    b()
} 

t(1);
t(()=>{console.log('passed')})

When you use = in function param definition, you no longer need ?

Upvotes: 1

Robbie Milejczak
Robbie Milejczak

Reputation: 5770

When you use the post bang like:

callback!();

what you're doing is asserting that, at this point in the interpretation of your code, callback will exist regardless of it being an optional value. So the typescript compiler thinks you're doing something like this:

doSomething('test', undefined)

because you told it that callback would exist.

Instead you should manually check for the value:

if(callback){
  callback();
}

This should clear up any errors

Upvotes: 3

Related Questions