Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.
like image 822
trusktr Avatar asked Jan 26 '17 00:01

trusktr


People also ask

How do you set a default value for properties in TypeScript?

To set default value for an object parameter:Type the object as having one or more optional properties. Set default value for each of the optional properties. Alternatively, set the entire object as optional, by setting all its properties to optional.

How do I set default value in property?

Right-click the control that you want to change, and then click Properties or press F4. Click the All tab in the property sheet, locate the Default Value property, and then enter your default value. Press CTRL+S to save your changes.

How do you assign a value to a model in TypeScript?

The type syntax for declaring a variable in TypeScript is to include a colon (:) after the variable name, followed by its type. Just as in JavaScript, we use the var keyword to declare a variable. Declare its type and value in one statement.

Can we have an interface with default properties in TypeScript?

In TypeScript, interfaces represent the shape of an object. They support many different features like optional parameters but unfortunately do not support setting up default values. However, you can still set up a TypeScript interface default value by using a workaround.


2 Answers

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
}
like image 153
Ali Baig Avatar answered Sep 20 '22 21:09

Ali Baig


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.

like image 25
Aluan Haddad Avatar answered Sep 20 '22 21:09

Aluan Haddad