Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在Typescript中定义对象变量的类型?_Javascript_Typescript - Fatal编程技术网

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

Javascript 如何在Typescript中定义对象变量的类型?,javascript,typescript,Javascript,Typescript,我在类a中有这个对象变量: class a { abc = { def: number = 22 // won't work } ghi: number = 23; // works .. 我如何定义(不使用接口的内联)对象内变量def的类型abc 我尝试使用这种语法,但它不会接受 可能的方式是使用断言和内联声明: class MyClass { abc = <{ def : number }>{ def: 1, }; } 因为ghi是

我在类
a
中有这个对象变量:

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

..
我如何定义(不使用接口的内联)对象内变量
def
的类型
abc


我尝试使用这种语法,但它不会接受

可能的方式是使用断言和内联声明:

class MyClass {
  abc = <{ def : number }>{
    def: 1,
  };  
}
因为ghi是a类的成员/财产,所以它是这样的:

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

仅供参考。不使用类型断言:

class a {
  abc : {def:number} = {
    def : 22  // Works
  }
  ghi: number = 23; // works
}
注意:在您的情况下,最好让编译器为您推断类型签名

class MyClass {
  // standard way how to define properties/members of a class
  public obj: number;
  private other: string;
}
class a {
  abc : {def:number} = {
    def : 22  // Works
  }
  ghi: number = 23; // works
}