Camden Clark Camden Clark - 3 years ago 111
TypeScript Question

Handling (type | undefined) checks in interfaces with Typescript

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


Answer Source

I could not reproduce it in, 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[];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download