How to set the value of a class property by default in a TypeScript declaration file?

fe i

declare class Foo extends Bar { foo: number } 

How to declare foo has a default value (or initial value), e.g. 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. 
+5
source share
3 answers

Your program is trying to accomplish two conflicting tasks.

  • It tries to declare that the class exists, but is actually implemented elsewhere / otherwise.
  • He is trying to define this implementation.

You need to determine which of these tasks you want to perform, and configure your program accordingly by removing either the initializer or the declare modifier.

+3
source

Try removing the declaration from your class definition. Using declare, it will determine the type of class. A type is defined only and should not have an implementation.

 class Foo extends Bar { foo: number = 60 } 
+10
source

You need a constructor to set default values ​​for a class property.

Try the following:

 declare class Foo extends Bar { foo: number; constructor(){ this.foo = 60; } } 

UPDATE: After a closer look at the code snippet, I noticed that you are using the declare keyword, in doing this, you just defined the class type, and this one does not require implementation.

UPDATE 2: You do not need a class constructor for this; you can initialize your properties with or without it.

If you delete the declare keyword, it should work fine.

 class Foo extends Bar { foo: number; constructor(){ this.foo = 60; } } 
-3
source

Source: https://habr.com/ru/post/1263368/


All Articles