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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24988956/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 02:55:36  来源:igfitidea点击:

How can I define a return type of void for a function in a Typescript interface?

typescript

提问by Alan2

I have this function:

我有这个功能:

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

I tried to define an interface but it's not working for me:

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

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

I get a message saying "unexpected token" on void

我在 void 上收到一条消息,说“意外的令牌”

回答by Ryan Cavanaugh

You have two options for syntax for a function-typed interface member, which are equivalent here:

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

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

or

或者

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

回答by Douglas

That is close to the "type literal" syntax, but the braces are required for that:

这接近于“类型文字”语法,但需要大括号:

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

This is the full syntax, and allows defining overloads, like this:

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

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