TypeScript编译遇'number | null'无法赋值给'number'错误,如何规避?
问题:TypeScript编译时null类型赋值报错
执行npm run build编译TypeScript代码时出现以下错误:
Type 'number | null' is not assignable to type 'number'. Type 'null' is not assignable to type 'number'.
对应的Index.ts中init方法代码如下:
public init(context: ComponentFramework.Context<IInputs>, notifyOutputChanged: () => void, state: ComponentFramework.Dictionary, container:HTMLDivElement) { // the increment value defaults to 1 if no increment input is detected, or it is zero. this._incrementValue = 1; if(context.parameters.incrementValue != null){ if(context.parameters.incrementValue.raw != 0){ this._incrementValue = context.parameters.incrementValue.raw; } } }
在对this._incrementValue赋值时触发上述错误,如何避免编译器针对null值的报错?
解决方案
方法1:补充raw值的null检查
虽然已经判断了context.parameters.incrementValue != null,但Power Apps组件的参数raw属性仍可能为null,因此需要额外检查raw是否非空:
public init(context: ComponentFramework.Context<IInputs>, notifyOutputChanged: () => void, state: ComponentFramework.Dictionary, container:HTMLDivElement) { this._incrementValue = 1; if(context.parameters.incrementValue != null && context.parameters.incrementValue.raw != null){ if(context.parameters.incrementValue.raw !== 0){ this._incrementValue = context.parameters.incrementValue.raw; } } }
方法2:使用非空断言操作符(!)
如果你能确保进入赋值分支时raw一定不为null,可以用!明确告诉编译器该值不会是null:
public init(context: ComponentFramework.Context<IInputs>, notifyOutputChanged: () => void, state: ComponentFramework.Dictionary, container:HTMLDivElement) { this._incrementValue = 1; if(context.parameters.incrementValue != null){ if(context.parameters.incrementValue.raw != 0){ this._incrementValue = context.parameters.incrementValue.raw!; } } }
注意:使用非空断言需保证运行时该值确实不会为null,否则会引发运行时错误。
方法3:用可选链+空值合并简化逻辑
通过?.(可选链)和??(空值合并)操作符,可以更简洁地处理null情况,同时保留默认值逻辑:
public init(context: ComponentFramework.Context<IInputs>, notifyOutputChanged: () => void, state: ComponentFramework.Dictionary, container:HTMLDivElement) { const rawValue = context.parameters.incrementValue?.raw; this._incrementValue = rawValue !== 0 && rawValue != null ? rawValue : 1; }
如果仅需要在raw为null或0时使用默认值,还可以进一步简化:
public init(context: ComponentFramework.Context<IInputs>, notifyOutputChanged: () => void, state: ComponentFramework.Dictionary, container:HTMLDivElement) { this._incrementValue = context.parameters.incrementValue?.raw ?? 1; }
内容的提问来源于stack exchange,提问作者user15235239
相关产品推荐
相关产品推荐

