Louis Coulet
Louis Coulet

Reputation: 4631

How to discriminate type and array of type in typescript?

In typescript, how can I discriminate between a user defined type and an array of such type?

type SomeType = { foo: string; };

function doSomething(x: SomeType | SomeType[]) {
    // Is x an array?
}

When the argument is a primitive type or an array, it is straightforward with typeof, but this does not work with user defined types.

Upvotes: 1

Views: 156

Answers (1)

Jérémie B
Jérémie B

Reputation: 11022

Use Array.isArray :

interface A { }

function someFunction(prop: A|A[]) {
    if (Array.isArray(prop)) {
        prop.length
    }
}

TS Playground

Upvotes: 2

Related Questions