这是我想动态化的对象。我怎样才能做到这一点? 我想在需要时在此添加更多字段。
request = {
header:{
consumingAppId:"USER",
userTypeCd : "S",
instanceId : "QA",
},
userInfo:{
firstName: "John",
lastName: "Doe"
}
}
答案 0 :(得分:0)
如果您提前知道可能的属性,则可以使用它们创建一个接口。您可以使用?
的所有可选属性。
interface MyRequest {
header: {
consumingAppId: string,
userTypeCd: string,
instanceId: string,
},
userInfo: {
firstName: string,
lastName: string,
nickName?: string, // example of an optional property on the userInfo object
},
metadata?: { // this entire metadata object can be left off
id: number; // but if metadata exists, it must have an id
price?: number;
}
}
const request: MyRequest = {
header: {
consumingAppId: "USER",
userTypeCd : "S",
instanceId : "QA",
},
userInfo: {
firstName: "John",
lastName: "Doe"
}
}
request.userInfo.nickName = 'scar face'; // legal
request.userInfo.favoriteColor = 'blue'; // illegal, because there's no favoriteColor in the type
有关更多信息,请参见documentation on optional properties。