undefined
undefined

Reputation: 6854

Typescript type guards don't work when extracting to a function

When I'm using the native code directly, typescript knows the correct type inside the block, for example:

function test(value: string | string[]) {

    if (Array.isArray(value)) {
        // ts knows that value is array
        return value;
    }

    return value;
}

But when I am trying to abstract the logic to a function it does not work anymore.

function isArray(value) {
  return Array.isArray(value);
}

function test(value: string | string[]) {

    if (isArray(value)) {
        return value;
    }

    return value;
}

There is a way to do this without explicitly write the as keyword?

Upvotes: 0

Views: 39

Answers (1)

toskv
toskv

Reputation: 31600

Typeguards have a special return type. You need to add it to your function as well.

function isArray(value): value is Array<any> {
    return Array.isArray(value);
}

Upvotes: 2

Related Questions