14

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.
4
  • 4
    Why do you need to set a default value for a declared class? Commented Jan 26, 2017 at 0:11
  • Good point! I suppose the runtime code does that anyway. Commented Jan 26, 2017 at 1:47
  • Haha, that should be the answer! Commented Jan 26, 2017 at 1:49
  • is the default value for class member 'undefined' as well or it is null? Commented Nov 20, 2018 at 21:00

3 Answers 3

29

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

I'm not the downvoter but I would suspect it is due to your assumption
4

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.

Comments

-6

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

3 Comments

"You need a constructor in order to set default values to class property." That is entirely false
Yes, you actually don't need a constructor for this, just my choice of class design. I'm updating this because i don't want people over reacting over nothing haha
How can it be reacting over nothing? You make a false, irrelevant claim.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.