1

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

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.