1

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.

2
  • 2
    Array.isArray Commented Feb 6, 2021 at 16:26
  • The missing piece, thank you! Commented Feb 6, 2021 at 16:37

1 Answer 1

2

Use Array.isArray :

interface A { }

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

TS Playground

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

1 Comment

Thank you! Is it the same isArray as in javascript: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… ?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.