简体   繁体   English

如何在Typescript中定义对象变量的类型?

[英]How can I define the types of an object variable in Typescript?

I have this object variable in the class a : 我在类a有这个对象变量:

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

..

How can I define (inline without using an interface) the type of the variable def that is inside the object abc ? 如何定义(内联而不使用接口)对象abc中的变量def的类型?

I tried using this syntax but it will not accept it. 我尝试使用这种语法,但它不会接受它。

The way it could be - is to use assert and inlined declaration: 它的方式是 - 使用断言和内联声明:

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

The same, but a bit more readable with explicit interface 相同,但显示界面更具可读性

interface IMyObject{
  def : number 
}

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

Check it here 在这里查看

And why this? 这是为什么?

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

because the ghi is the member/property of class a - so it is just like this: 因为ghi是类a的成员/属性 - 所以它就像这样:

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

Just FYI. 仅供参考。 Without using a type assertion: 不使用类型断言:

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

Note: in your case its best to let the compiler infer the type signature for you. 注意:在您的情况下,最好让编译器为您推断类型签名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM