0

In typescript, if I use this,

Array.isArray(value) ? [value] : value

...it works fine. But if I use a utility function to check it if is array then Typescript complains with error message Argument of type Item[] | Item[][] is not assignable to type Item | Item[].

const isArray = (value: any) => Array.isArray(value)

isArray(value) ? [value] : value // Throws error
4
  • Try const isArray = (value: any): value is any[] => Array.isArray(value) Commented Feb 24, 2021 at 9:16
  • 2
    Why not just const { isArray } = Array? Given that the function only does that one thing. Or is that just an example? Commented Feb 24, 2021 at 9:19
  • @LionelRowe That's just my personal preference to have like all the utility functions in one file be it as simple as checking array, string, and so on... 😅 Commented Feb 24, 2021 at 9:22
  • 2
    In that case yeah, just use const { isArray } = Array. No need to create a new function just to call an existing function. Commented Feb 24, 2021 at 9:29

1 Answer 1

1

Try:

const isArray = (value: any): value is any[] => Array.isArray(value)

You can learn about this more here

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.