Javascript 如何在 TypeScript 声明文件中设置默认类属性值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41863918/
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
How to set default class property value in TypeScript declaration file?
提问by trusktr
f.e., I have
fe,我有
declare class Foo extends Bar {
foo: number
}
How do I declare that foohas a default value (or initial value) of, say, 60.
我如何声明它foo的默认值(或初始值)为 60。
I tried
我试过
declare class Foo extends Bar {
foo: number = 60
}
but I get an error like
但我收到一个错误
4 foo: number = 60
~~
path/to/something.js/Foo.d.ts/(4,28): error TS1039: Initializers are not allowed in ambient contexts.
采纳答案by Aluan Haddad
Your program attempts to perform two mutually contradictory tasks.
您的程序尝试执行两个相互矛盾的任务。
- It tries to declarethat a class exists but is actually implementedelsewhere/otherwise.
- It tries to definethat implementation.
- 它试图声明一个类存在,但实际上是在别处/其他地方实现的。
- 它试图定义该实现。
You need to determine which of these tasks you wish to perform and adjust your program accordingly by removing either the initializer or the declaremodifier.
您需要确定您希望执行哪些任务,并通过删除初始化程序或declare修饰符来相应地调整您的程序。
回答by Ali Baig
Try removing declare from your class definition. By using declare it will define a class type. The type is only defined, and shouldn't have an implementation.
尝试从您的类定义中删除声明。通过使用声明,它将定义一个类类型。类型只是定义的,不应该有实现。
class Foo extends Bar {
foo: number = 60
}
回答by Matheus Da Silva Primo
You need a constructor in order to set default values to class property.
您需要一个构造函数来为类属性设置默认值。
Try this:
尝试这个:
declare class Foo extends Bar {
foo: number;
constructor(){
this.foo = 60;
}
}
UPDATE:After taking a closer look at your code snippet i noticed you are using the keyword declare, doing so, you just defined a class type and this one requires no implementation.
更新:仔细查看您的代码片段后,我注意到您正在使用关键字声明,这样做,您只是定义了一个类类型,而这个不需要实现。
UPDATE 2:A class constructor is not necessary for this, you may initialize your properties with or without one.
更新 2:为此不需要类构造函数,您可以使用或不使用属性来初始化您的属性。
If you remove the keyword declare it should work fine.
如果您删除关键字声明它应该可以正常工作。
class Foo extends Bar {
foo: number;
constructor(){
this.foo = 60;
}
}

