问题
参数值maxORhealth
会提示以下错误;在VS代码中:
Type 'undefined' is not assignable to type 'number'.ts(2345)
...并且不确定如何浏览此错误。
类定义
class Vitals implements IVitals
{
vitals!:
{
HealthValue: number | undefined;
StrengthValue?: number | undefined;
ManaValue?: number | undefined;
StaminaValue?: number | undefined;
IntelectValue?: number | undefined;
TuneValue?: number | undefined;
};
/// CONSTRUCTORS
constructor()
constructor(maxORhealth: number)
constructor(maxORhealth: number, maxORstrength: number)
constructor(maxORhealth: number,
maxORstrength: number,
mana: number,
stamina: number,
intelect: number,
tune: number)
constructor(maxORhealth?: number,
maxORstrength?: number,
mana?: number,
stamina?: number,
intelect?: number,
tune?: number)
{
if (Number.isInteger(maxORhealth) && maxORstrength === undefined && mana === undefined)
{
this.vitals.HealthValue = getRandomInt(maxORhealth); <= Error .ts(2345)
this.vitals.StrengthValue = getRandomInt(maxORhealth);
this.vitals.ManaValue = getRandomInt(maxORhealth);
this.vitals.StaminaValue = getRandomInt(maxORhealth);
this.vitals.IntelectValue = getRandomInt(maxORhealth);
this.vitals.TuneValue = getRandomInt(maxORhealth);
}
else if (Number.isInteger(maxORhealth) && maxORstrength === undefined)
{
this.vitals.HealthValue = maxORhealth;
this.vitals.StrengthValue = getRandomInt(maxORstrength!);
this.vitals.ManaValue = getRandomInt(maxORstrength!);
this.vitals.StaminaValue = getRandomInt(maxORstrength!);
this.vitals.IntelectValue = getRandomInt(maxORstrength!);
this.vitals.TuneValue = getRandomInt(maxORstrength!);
}
else
{
this.vitals.HealthValue = maxORhealth;
this.vitals.StrengthValue = maxORstrength;
this.vitals.ManaValue = mana;
this.vitals.StaminaValue = stamina;
this.vitals.IntelectValue = intelect;
this.vitals.TuneValue = tune;
}
}
}
期望的影响
我希望本节课有三个constructors
,如下所示:
constructor()
constructor(maxORhealth: number)
constructor(maxORhealth: number, maxORstrength: number)
constructor(maxORhealth: number, maxORstrength: number, mana: number, stamina: number, intelect: number, tune: number)
...(希望)有一个实用的(没有过多的JS花式)解决方案。
答案 0 :(得分:1)
错误源自以下语句:
Number.isInteger(maxORhealth)
maxORhealth
的类型为number | undefined
。因为它是构造函数的可选参数,所以它可以是number
或undefined
。
Number.isInteger
仅接受类型为number
的参数。因此TypeScript抱怨,因为maxORhealth
也可能是数字。
要解决此问题,您可以执行以下两项操作之一。您可以像这样为undefined
引入其他支票:
if (maxORhealth !== undefined && Number.isInteger(maxORhealth) && maxORstrength === undefined && mana === undefined) {
// ^^^^^^^^^^^^^^^^^^^^^^^^^
或者,考虑到Number.isInteger(undefined)
被正确处理并仅返回false
,您还可以说服TypeScript仍然可以。为此,您可以使用非空断言后缀!
运算符:
Number.isInteger(maxORhealth!)
// ^
此运算符告诉TypeScript maxORhealth
不是undefined
也不是null
。