Typescript 打字很严格。状态属性不是未定义的
在严格模式下,typescript警告可能使用未定义的属性。令人惊讶的是,它能够检测到阻止这种情况发生的逻辑(正如它在“标准检查”一行中所做的那样)Typescript 打字很严格。状态属性不是未定义的,typescript,strict,Typescript,Strict,在严格模式下,typescript警告可能使用未定义的属性。令人惊讶的是,它能够检测到阻止这种情况发生的逻辑(正如它在“标准检查”一行中所做的那样) 但是,如果逻辑像“自定义检查”中那样更隐蔽,则不会。我不希望它是超智能的,但如何声明属性已验证?(示例很简单,但在更复杂的情况下可能是必要的)您可以使用is class AClass{ aProp?:number=undefined; HasAProp():boolean{return this.aProp!==undefined;
但是,如果逻辑像“自定义检查”中那样更隐蔽,则不会。我不希望它是超智能的,但如何声明属性已验证?(示例很简单,但在更复杂的情况下可能是必要的)您可以使用
is
class AClass{
aProp?:number=undefined;
HasAProp():boolean{return this.aProp!==undefined;}
}
let anInst=new AClass;
if (anInst.aProp) // standard check
Math.sqrt(anInst.aProp);
if (anInst.HasAProp()) // custom check
Math.sin(anInst.aProp); // ts error: Argument of type 'number | undefined' is not assignable to parameter of type 'number'.
我不确定是否可以不将
aProp
作为参数传递到HasAProp()
中。您可以使用is
class AClass{
aProp?:number=undefined;
HasAProp():boolean{return this.aProp!==undefined;}
}
let anInst=new AClass;
if (anInst.aProp) // standard check
Math.sqrt(anInst.aProp);
if (anInst.HasAProp()) // custom check
Math.sin(anInst.aProp); // ts error: Argument of type 'number | undefined' is not assignable to parameter of type 'number'.
我不确定是否可以不将
aProp
作为参数传递到HasAProp()
中。在这种情况下,如果TypeScript编译器无法确定属性不是null
或未定义的
,则可以使用!
(非null断言运算符)
就你而言,这意味着:
class AClass {
aProp?: number = undefined;
HasAProp(aProp: this['aProp']): aProp is number {
return aProp !== undefined;
}
}
let anInst = new AClass;
if (anInst.aProp)
Math.sqrt(anInst.aProp);
if (anInst.HasAProp(anInst.aProp))
Math.sin(anInst.aProp);
这有效地告诉编译器,您知道该属性是在此时定义的,即使编译器无法理解它
此处的详细信息:在这种情况下,如果TypeScript编译器无法确定属性不是
null
或未定义的,则可以使用!
(非null断言运算符)
就你而言,这意味着:
class AClass {
aProp?: number = undefined;
HasAProp(aProp: this['aProp']): aProp is number {
return aProp !== undefined;
}
}
let anInst = new AClass;
if (anInst.aProp)
Math.sqrt(anInst.aProp);
if (anInst.HasAProp(anInst.aProp))
Math.sin(anInst.aProp);
这有效地告诉编译器,您知道该属性是在此时定义的,即使编译器无法理解它
这里的更多信息:我不知道x是y
语法,但我想你可以这样做:HasAProp():这是AClass&{aProp:number}
。我不知道x是y
语法,但我想你可以这样做:HasAProp():这是AClass&{aProp:number}
。