0

Here, I'm trying to check if there's a "booster" (Card[]) that is in the boostersToGo variable in a player interface. If there is, I want to shift() it and make that the currentBooster.

However, Typescript is giving me an error:

message: 'Type 'Card[] | undefined' is not assignable to type 'Card[]'.
Type 'undefined' is not assignable to type 'Card[]'.'

My editor (VSCode) is underlining player.currentBooster in red here. What's going on? I have had similar issues before using typescript but have hacked around them a little bit. What's the proper way to deal with this?

if (player.boostersToGo.length > 0) {
    player.currentBooster = player.boostersToGo.shift()
}
//player is guaranteed to fit the interface Player because that's what's explicitly passed into the function

export interface Player {
    boostersToGo: Card[][]
    currentBooster: Card[]
    picks: Card[][]
    human: boolean
}

export interface Card {
    name: string
    manaCost: string
    colors?: string[]
    cmc: number
    types: string[]
    rarity: string
    imageUrl: string
    pick?: boolean
}

Thanks!

2
  • Try this <Card[]>player.boostersToGo.shift() Commented Jul 26, 2017 at 5:52
  • Fixed. I guess I have to cast everything that could be undefined? Thanks. Commented Jul 26, 2017 at 6:02

1 Answer 1

1

I could not reproduce it in http://www.typescriptlang.org, so maybe it's related with your TypeScript / IntelliSense version, which will also change your lib.d.ts definitions.

It may be worth trying to quickly run a bigger portion of your problematic code in there and see if the problem persists. If it doesn't, maybe upgrading to the latest TypeScript version or updating VSCode will help.

Otherwise, you can always enforce a type with Type Assertion (casting):

if (player.boostersToGo.length > 0) {
    player.currentBooster = player.boostersToGo.shift() as Card[];
}
Sign up to request clarification or add additional context in comments.

2 Comments

For the error to be effected the strictNullChecks (or the encompassing strict) compiler option needs to be set to true.
Another option is to use TypeScript's non-null assertion operator: player.currentBooster = player.boostersToGo.shift()!;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.