如何让打字稿停止抱怨函数上的静态成员?

时间:2017-11-20 18:46:27

标签: typescript

我的例子几乎解释了这个问题。

但基本上,我在尝试理解如何在下面的代码中向函数添加静态成员时编写有效的打字稿

export const ZoomPanelControl = (props) => undefined;
ZoomPanelControl.Item = (props) => undefined;

link for fiddle

2 个答案:

答案 0 :(得分:1)

向函数添加属性的最直接方法是使用Object.assign()在单个语句中创建function-with-property:

export const ZoomPanelControl = Object.assign(
    (props) => undefined,
    { Item: (props) => undefined }
);

这会产生((props: any) => any) & { Item: (props: any) => any; }类型的对象,这是你想要的:

ZoomPanelControl(123); // okay
ZoomPanelControl.Item(456); // okay
祝你好运!

答案 1 :(得分:0)

如果你需要"差距"在定义函数和分配属性之间,您可以使用类型断言:

type Example = {
    (props: any): any;
    [key: string]: (props: any) => any;
}

const ZoomPanelControl = <Example>((props) => undefined);

//...

ZoomPanelControl.Item = (props) => undefined;

您可以将类型置于类型断言中,但这只是要读取的一行代码,这就是我将其拉出Example类型的原因。

编译器仍然会针对((props) => undefined)类型的签名对Example进行一般性检查 - 因此存在类型安全性,而不是一种常见的替代方法:

const ZoomPanelControl: Example = <any>((props) => undefined);

如果您不想允许&#34;任何字符串作为键,那么您可以将其限制为已知成员...

type Example = {
    (props: any): any;
    Item: (props: any) => any;
}

如果你在一次点击中设置了这个,jcalz answer has the benefit of type-inference(它有效地为你提供了我上一个代码块中的类型,但是免费)。

相关问题