Reputation: 4631
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
Reputation: 11022
Use Array.isArray
:
interface A { }
function someFunction(prop: A|A[]) {
if (Array.isArray(prop)) {
prop.length
}
}
Upvotes: 2