我正在尝试将二十一点作为学习 TypeScript 的练习。当我运行程序时,玩家成功地从鞋子中获得了两张牌,但我收到了警告Argument of type 'Card | undefined' is not assignable to parameter of type 'Card'.
这是我的代码:
class Card {
suit: string;
value: number;
name: string;
constructor(suit: string, value: number, name: string) {
this.suit = suit;
this.value = value;
this.name = name;
}
greet() {
console.log(`This card is a ${this.value} of ${this.suit}`)
}
}
class Deck {
static suits = ["Diamonds", "Clubs", "Hearts", "Spades"]
static cardTypes = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace"]
cards: Card[] = [];
makeDeck() {
let cards: Card[] = [];
for (let i = 0; i < Deck.suits.length; i++) {
for (let j = 0; j < Deck.cardTypes.length; j++) {
let value = Deck.cardTypes[j];
let numValue: number;
let name: string;
if (
value === "Jack" ||
value === "Queen" ||
value === "King"
) {
numValue = 10
} else if (value === "Ace") {
numValue = 11
}
else {
numValue = parseInt(Deck.cardTypes[j]);
}
name = `${value} of ${Deck.suits[i]}`
cards.push(new Card(Deck.suits[i], numValue, name))
}
}
return cards;
}
constructor() {
this.cards = this.makeDeck()
}
presentDeck() {
console.log(this.cards)
}
}
class Shoe {
numberOfDecks: number;
cards: Card[] = [];
constructor(numberOfDecks: number) {
this.numberOfDecks = numberOfDecks
this.cards = this.makeShoe()
}
错误在shoe.dealCard()最后的零件上。我不确定为什么该类型有两部分,Card 和 undefined。而且我不确定什么是未定义的。
暮色呼如
相关分类