Typescript 添加字段';x';如果输入对象具有属性';x';
假设我有一个类EventCard,它接受一个包含一些属性的对象。其中一个字段(在类中)是可选的Typescript 添加字段';x';如果输入对象具有属性';x';,typescript,Typescript,假设我有一个类EventCard,它接受一个包含一些属性的对象。其中一个字段(在类中)是可选的 const onCardChangeEvent = function(newCard) { if (newCard["choices"]) { currentChosenCard.value = new EventCard({ name: newCard.name, event: newCard.event, cardType: ne
const onCardChangeEvent = function(newCard) {
if (newCard["choices"]) {
currentChosenCard.value = new EventCard({
name: newCard.name,
event: newCard.event,
cardType: newCard.cardType,
description: newCard.description,
choices: newCard.choices
});
} else {
currentChosenCard.value = new EventCard({
name: newCard.name,
event: newCard.event,
cardType: newCard.cardType,
description: newCard.description
});
}
};
我是否可以将此代码归结为类实例化,而不是检查“choices”属性是否存在?使用ES6对象分解的组合,然后构造其
choices
属性有条件存在的有效负载?从这个意义上讲,您可以避免大量代码重复:
const onCardChangeEvent = function({ name, event, cardType, description, choices }) {
const payload = {
name,
event,
cardType,
description
};
if (choices)
payload.choices = choices;
currentChosenCard.value = new EventCard(payload);
};
看起来@EdwinCarlsson可以将其缩短为
const onCardChangeEvent=(有效负载)=>{currentChosenCard.value=new EventCard(有效负载);}
,除非有效负载
中存在不应发送给事件卡构造函数的字段。