What types should I specify for foo and BAR in the ExampleClass ExampleClass below?

 class ExampleClass { private foo = { one: 1, two: 2 }; private static BAR = { one: 'one', two: 'three' } } 

Cases where such annotation is necessary:

enter image description here

Text version:

 import { Vue, Component, Prop } from 'vue-property-decorator'; @Component export default class Bootstrap4AlertsCodeGenerator extends Vue { static CONTEXT_CSS_CLASSES: object = { PRIMARY: 'primary', SECONDARY: 'secondary', SUCCESS: 'success', }; contextCssClass: string = Bootstrap4AlertsCodeGenerator.CONTEXT_CSS_CLASSES.SECONDARY; public get isSelectContextCssClassRadiobuttonActive(): (contextCssClass: string) => boolean { return contextCssClass => this.contextCssClass === contextCssClass; } } 

Mistake:

 TS2339: Property 'SECONDARY' does not exist on type 'object'. 
  • 1. use any instead of object 2. declare a contract or alias 3. get access by key through square brackets CONTEXT_CSS_CLASSES['SECONDARY'] ..... When you use the object | Object type object | Object object | Object - you tell the compiler that CONTEXT_CSS_CLASSES is a simple object without attributes - overthesanity
  • @overthesanity, thank you for the answer! The first method does not work - after all, the main thing for which TypeScript is needed is typification (the other possibilities such as static fields are available in JavaScript with the necessary Babel plug-ins). The third way is also not very - almost hardcoding. But the second is more interesting. - Bokov Gleb
  • @overthesanity, could you give an example of the second method in the answer based on the code in the question? In the documentation for the TypeScipt-interfaces, I did not find anything suitable. - Bokov Gleb

1 answer 1

One solution to the error: remove type indication

 static CONTEXT_CSS_CLASSES = { PRIMARY: 'primary', SECONDARY: 'secondary', SUCCESS: 'success', }; 

In this case, the type will be displayed automatically, and the error will no longer appear.


You can also directly specify the type in the ad. It is quite simple to find out the type of the literal being assigned; this will be the same literal, in which instead of the property values ​​will be indicated their type.

For example, the literal

 { PRIMARY: 'primary', SECONDARY: 'secondary', SUCCESS: 'success', } 

Has a type

 { PRIMARY: string, SECONDARY: string, SUCCESS: string } 

As a result, the field definition will look like this:

 static CONTEXT_CSS_CLASSES: { PRIMARY: string, SECONDARY: string, SUCCESS: string } = { PRIMARY: 'primary', SECONDARY: 'secondary', SUCCESS: 'success', }; 

To reduce the ad a little bit, you can declare alias for the specified type.

 type customType = { PRIMARY: string, SECONDARY: string, SUCCESS: string }; static CONTEXT_CSS_CLASSES: customType = { PRIMARY: 'primary', SECONDARY: 'secondary', SUCCESS: 'success', };