Chris
Chris

Reputation: 27394

Specify arguments of Typescript function callback

I have a callback currently defined like so:

onShow: Function;

And is called like so:

if (this.onShow) {
    this.onShow({ $currentPosition: this.currentLatLngPosition });
}

The main issue with this is that its not typesafe. How can I change the signature of onShow to have better type safety?

I found out I could define it a little better like so

onShow: () => void;

But I could not figure out how to get the correct function arguments in there. This doesnt work:

onShow: ({ $currentPosition: google.maps.LatLng }) => void;

Note the weird json parameter syntax is an Angular component callback requirement.

Upvotes: 0

Views: 346

Answers (1)

Sebastian Sebald
Sebastian Sebald

Reputation: 16856

interface Config {
    $currentPosition: string; // Or whatever the type of the property is.
}

type myFunc = (config: Config) => void;

You do not have to create an interface:

type myFunc = (config: { $currentPosition:string }) => void;

Upvotes: 3

Related Questions