2017-07-26 313 views
0

在这里,我试图检查播放器界面中的boostersToGo变量是否存在“助推器”(Card [])。如果有的话,我想转移()它并使之成为currentBooster。在与Typescript的接口中处理(type | undefined)检查

然而,打字稿是给我的错误:

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

我的编辑(VSCode)在红这里强调player.currentBooster。这是怎么回事?在使用打字稿之前,我遇到了类似的问题,但是他们已经在他们身上劈了一下。处理这个问题的正确方法是什么?

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 
} 

谢谢!

+0

试试这个 player.boostersToGo.shift() – Sreemat

+0

固定。我想我必须投下所有可能未定义的东西?谢谢。 –

回答

1

我无法重现它在http://www.typescriptlang.org,所以也许这与您的TypeScript/IntelliSense版本,这也将改变你的lib.d.ts定义有关。

它可能是值得尝试快速运行在你那里有问题的代码的更大一部分,看看问题是否依然存在。如果没有,也许升级到最新的TypeScript版本或更新VSCode将有所帮助。

否则,你总是可以强制执行类型与Type Assertion (casting)

if (player.boostersToGo.length > 0) { 
    player.currentBooster = player.boostersToGo.shift() as Card[]; 
} 
+2

对于要产生的错误,'strictNullChecks'(或包含'strict')编译器选项需要设置为'true'。 – cartant

+2

另一个选择是使用TypeScript的[非null断言运算符](https://github.com/Microsoft/TypeScript/wiki/What's-new-in-TypeScript#non-null-assertion-operator):'player.currentBooster = player.boostersToGo.shift()!;' – cartant