How do I determine the types of an object variable in Typescript?

I have this object variable in a class a

:

class a {
  abc = {
    def: number = 22  // won't work
  }
  ghi: number = 23; // works

..

      

How can I determine (inline without using an interface) the type of a variable def

that is inside an object abc

?

I tried using this syntax but it won't accept it.

+3


source to share


2 answers


How can it be - use assert and inline assertion:

class MyClass {
  abc = <{ def : number }>{
    def: 1,
  };  
}

      

The same, but slightly more readable with an explicit interface

interface IMyObject{
  def : number 
}

class MyClass1 {
  abc = <IMyObject>{
    def: 1,
  };  
}

      

Check here



And why is that?

class a {
  abc = {
    def: number = 22  // won't work
  }
  ghi: number = 23; // works

      

because ghi is an element / property of class a, so it looks like this:

class MyClass {
  // standard way how to define properties/members of a class
  public obj: number;
  private other: string;
}

      

+2


source


Just FYI. Without using a type assertion:

class a {
  abc : {def:number} = {
    def : 22  // Works
  }
  ghi: number = 23; // works
}

      



Note: in your case, it is best to let the compiler infer the type signature for you.

0


source







All Articles