我想知道是否可以在脚本情况下将变量标记为特定类型,而无需为TS编译器定义新变量?我将其视为带有“ as”的RoleCard,但我不想定义一个变量
const card = this.deck.shift();
switch (card.type) {
case CardType.ROLE:
const roleCard = card as RoleCardMeta;
const activeCard: ActiveCard = {
remainingTurns: _.random(roleCard.minTurns, roleCard.maxTurns),
roleCard,
};
this.activeCards.push();
break;
}
最好的祝福
最佳答案
在type
文字和联合类型上使用类型防护:
interface CardBase {
someField: any;
}
enum CardType {
ROLE,
OTHER
}
interface RoleCardMeta extends CardBase {
type: CardType.ROLE;
minTurns: number;
maxTurns: number;
}
interface OtherCardMeta extends CardBase {
type: CardType.OTHER;
otherField: string;
}
type Card = RoleCardMeta
| OtherCardMeta;
function test(card: Card) {
switch (card.type) {
case CardType.ROLE:
console.log(card.minTurns, card.maxTurns);
break;
case CardType.OTHER:
console.log(card.otherField);
break;
}
}
关于javascript - 如何在 typescript 中指示航类的打字,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48608190/