Typescript - 带有接口的类的默认参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18640153/
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
Typescript - Default parameters on class with interface
提问by Grofit
I have a scenario where I have an interface which has a method like so:
我有一个场景,我有一个接口,它有一个像这样的方法:
interface SomeInterface
{
SomeMethod(arg1: string, arg2: string, arg3: boolean);
}
And a class like so:
和这样的类:
class SomeImplementation implements SomeInterface
{
public SomeMethod(arg1: string, arg2: string, arg3: boolean = true){...}
}
Now the problem is I cannot seem to tell the interface that the 3rd option should be optional or have a default value, as if I try to tell the interface there is a default value I get the error:
现在的问题是我似乎无法告诉界面第三个选项应该是可选的或具有默认值,就好像我试图告诉界面有一个默认值我收到错误:
TS2174: Default arguments are not allowed in an overload parameter.
TS2174: Default arguments are not allowed in an overload parameter.
If I omit the default from the interface and invokes it like so:
如果我从界面中省略默认值并像这样调用它:
var myObject = new SomeImplementation();
myObject.SomeMethod("foo", "bar");
It complains that the parameters do not match any override. So is there a way to be able to have default values for parameters and inherit from an interface, I dont mind if the interface has to have the value as default too as it is always going to be an optional argument.
它抱怨参数不匹配任何覆盖。那么有没有办法能够为参数设置默认值并从接口继承,我不介意接口是否也必须将值设为默认值,因为它总是一个可选参数。
回答by Ryan Cavanaugh
You can define the parameter to be optional with ?
:
您可以使用以下命令将参数定义为可选?
:
interface SomeInterface {
SomeMethod(arg1: string, arg2: string, arg3?: boolean);
}