Reputation: 381
I have a code like this:
function checkDefined(v: any): boolean { // external function
return v !== undefined
}
function mult(m?: number): number {
if (checkDefined(m))
return m * 3; // <<< Object is possibly 'undefined'.
if (m !== undefined)
return m * 3; // OK
throw new Error('"m" is not defined"')
}
How to check with external function if 'm' is defined?
Upvotes: 1
Views: 108
Reputation: 37918
You can use a type guard (expression that performs a runtime check that guarantees the type in some scope):
function checkDefined<T>(v: T | undefined): v is T {
return v !== undefined
}
Upvotes: 1