trusktr
trusktr

Reputation: 45454

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

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

Answers (3)

Aluan Haddad
Aluan Haddad

Reputation: 31803

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.

Upvotes: 4

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

Ali Baig
Ali Baig

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

Related Questions