我在类 a
中有这个对象变量:
class a {
abc = {
def: number = 22 // won't work
}
ghi: number = 23; // works
..
我如何定义(内联而不使用接口(interface))对象 abc
中的变量 def
的类型?
我尝试使用这种语法,但它不接受。
最佳答案
可能的方式是使用断言和内联声明:
class MyClass {
abc = <{ def : number }>{
def: 1,
};
}
相同,但使用显式接口(interface)更具可读性
interface IMyObject{
def : number
}
class MyClass1 {
abc = <IMyObject>{
def: 1,
};
}
查一下here
为什么会这样?
class a {
abc = {
def: number = 22 // won't work
}
ghi: number = 23; // works
因为 ghi 是类 a 的成员/属性 - 所以它就像这样:
class MyClass {
// standard way how to define properties/members of a class
public obj: number;
private other: string;
}
关于javascript - 如何在 Typescript 中定义对象变量的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27339590/