如何在Typescript接口中为函数定义void的返回类型?

时间:2014-07-28 05:36:04

标签: typescript

我有这个功能:

   network = (action): void =>{
        if (action) {
            this.action = action;
            this.net = true;
            this.netd = true;
        } else {
            this.action = null;
            this.net = false;
            this.netd = false;
        }
    }

我试图定义一个界面,但它对我不起作用:

interface IStateService {
    network: (action: string): void;
}

我在void

上收到一条消息“意外令牌”

2 个答案:

答案 0 :(得分:35)

对于函数类型的接口成员,您有两种语法选项,它们在此处等效:

interface IStateService {
    network: (action: string) => void;
}

interface IStateService {
    network(action: string): void;
}

答案 1 :(得分:4)

接近"类型文字"语法,但需要大括号:

interface IStateService {
    network: { (action: string): void; }
}

这是完整的语法,允许定义重载,如下所示:

interface IStateService {
    network: {
        (): string;
        (action: string): void;
    }
}