Reputation: 45454
f.e., I have
declare class Foo extends Bar {
foo: number
}
How do I declare that foo
has a default value (or initial value) of, say, 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.
Upvotes: 14
Views: 30293
Reputation: 31803
Your program attempts to perform two mutually contradictory tasks.
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.
Upvotes: 4
Reputation: 33
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.
If you remove the keyword declare it should work fine.
class Foo extends Bar {
foo: number;
constructor(){
this.foo = 60;
}
}
Upvotes: -6
Reputation: 3867
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
}
Upvotes: 29