DenniLa2
DenniLa2

Reputation: 381

How to check defined variable with external method / function in typescript

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?

Sandbox here

Upvotes: 1

Views: 108

Answers (1)

Aleksey L.
Aleksey L.

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
}

Playground

Upvotes: 1

Related Questions