Javascript 我应该使用new在typescript类中创建对象属性吗?
下面是我的Typescript类和接口:Javascript 我应该使用new在typescript类中创建对象属性吗?,javascript,typescript,Javascript,Typescript,下面是我的Typescript类和接口: interface ITest { qs: ITestQuestion[]; message: string; } interface ITestQuestion { answer: string; } class QuestionHomeController { test: ITest = { qs: null, message: string = "xxxxx" }
interface ITest {
qs: ITestQuestion[];
message: string;
}
interface ITestQuestion {
answer: string;
}
class QuestionHomeController {
test: ITest = {
qs: null,
message: string = "xxxxx"
}
constructor() {
this.test.qs = // << setting to An Array of Test Questions
}
}
接口测试{
qs:ITestQuestion[];
消息:字符串;
}
接口问题{
答:字符串;
}
类控制器{
测试:ITest={
qs:null,
消息:string=“xxxxx”
}
构造函数(){
this.test.qs=/如果您正在寻找初始化数组的方法,只需使用[]
:
interface ITest {
qs: ITestQuestion[];
}
interface ITestQuestion {
answer: string;
}
class QuestionHomeController {
test: ITest;
constructor() {
// initialize test
this.test =
{
qs: [
{ answer: 'first answer' },
{ answer: 'second answer' }
]
};
}
}
我应该在构造函数中创建一个新的测试对象吗
你的选择
这也是我声明接口的正确方法吗
对
更新
如果在我的类中有一个类似于“ready”的属性,那么我应该如何声明ready:string=null;在我的构造函数之前,还是应该声明:ready:string;然后在构造函数中do ready=null
如果我已经有值message:string='defaultmessage';
我会在变量声明中执行。如果我需要从服务器加载它,我会在构造函数中执行
更新2
如果您有一个类似test的属性,其中一个属性是您知道的,另一个是从服务器加载的qs,该怎么办
我会这样做:
interface ITestQuestion {
answer: string;
}
interface ITest {
local: string;
server: ITestQuestion[];
}
class QuestionHomeController {
test: ITest = {
local: 'something',
server: []
};
constructor() {
// request from server then:
this.test.server = [
{ answer: 'first answer' },
{ answer: 'second answer' }
];
}
}
如果有一个叫做“ready”的地方在我的类中,那么我应该如何声明ready:string=null;在我的构造函数之前,还是应该声明:ready:string;然后在构造函数中do ready=null;?很抱歉一直打扰您,但是如果您有一个对象属性,比如test,其中一个属性在您知道的范围内,另一个q从ser加载,该怎么办因为它是一个对象,我想我需要在构造函数中初始化它。对吗?