2017-05-10 217 views
0

的指定参数我现在像这样定义的回调:打字稿回调函数

onShow: Function; 

,被称为像这样:

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

与此主要问题是,它不是类型安全的。如何更改onShow的签名以获得更好的类型安全性?

我发现我可以稍微更好地定义它像这样

onShow:() => void; 

但我无法弄清楚如何得到正确的函数参数在里面。这不工作:

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

请注意怪异的json参数语法是一个角度组件回调要求。

+0

您可以在此处找到有关定义功能签名的更多信息:https://www.typescriptlang.org/docs/handbook/functions.html –

回答

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

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

您不必创建一个接口:

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