简体   繁体   English

如何在TypeScript声明文件中设置默认的类属性值?

[英]How to set default class property value in TypeScript declaration file?

fe, I have fe,我有

declare class Foo extends Bar {
    foo: number
}

How do I declare that foo has 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.

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
}

Your program attempts to perform two mutually contradictory tasks. 您的程序尝试执行两个相互矛盾的任务。

  1. It tries to declare that a class exists but is actually implemented elsewhere/otherwise. 它试图声明一个类存在,但实际上是在其他地方实现的
  2. It tries to define that 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 declare modifier. 您需要确定要执行以下哪些任务,并通过删除初始化程序或declare修饰符来相应地调整程序。

You need a constructor in order to set default values to class property. 您需要一个构造函数才能将默认值设置为class属性。

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. 更新:仔细查看了您的代码片段后,我注意到您正在使用关键字define,这样做只是定义了一个类类型,而该类不需要任何实现。

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;
      }  
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM