Code:
public get scaleString(): string {
const previewScale = !ObjectHelper.isNullOrUndefined(this.previewWidth) && !ObjectHelper.isNullOrUndefined(this.realWidth)
// Object is possibly 'undefined'
? this.previewWidth / this.realWidth
: 1;
const scaleInPercent = previewScale * this.scale * 100;
return `${scaleInPercent.toFixed(2)}%`;
}
ObjectHelper method:
public static isNullOrUndefined(v: object | string | boolean | number | null | undefined): boolean {
return v === undefined || v === null;
}
What I get is a visual studio code / TypeScript error:
- Object is possibly ‘undefined’
One way would be to add if statements:
const previewScale = this.previewWidth !== undefined && this.previewWidth !== null && this.realWidth !== undefined && this.realWidth !== null
? this.previewWidth / this.realWidth
: 1;
Is it possible to convince TypeScript that the upper function ObjectHelper.IsNullOrUndefined checked that already?
2
Answers
You just need to make
isNullOrUndefined
a type guard:Playground Link
Might I just suggest you can use
== null
as a replacement for the functionx == null
will be true if x isnull
orundefined
. It’s short, idiomatic to JS and TS understands it:Playground Link
Yes, you can. You can define the
isNullOrUndefined
like thisTS Playground
Edit: Even better
you can define it using Extract as:
This way you’ll be able to statically extract the
null
orundefined
based on the input typeTS Playground