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
}