'Typescript: how to name array of strings that could be undefined?
I'm using Typescript in my React Native app and I define the following array:
const arr: string[] = Platform.select({
ios: ["a", "b", "c"],
android: ["a", "b", "c"]
})
VsCode underlines arr and tells me Type 'string[] | undefined' is not assignable to type 'string[]', so I changed it to
const arr: string[] | undefined = Platform.select({
ios: ["a", "b", "c"],
android: ["a", "b", "c"]
})
VsCode removes the underline on arr in the definition, but when I use it in my code it underlines it there and says Argument of type 'string[] | undefined' is not assignable to parameter of type 'string[]'
I think the problem is that Platform.select() might return undefined, but then I'm using arr in my code for operations that require it to have type string[] instead of string[]. How can I modify my code to remove all these warnings?
Solution 1:[1]
You can give an empty array as the default value when Platform.select returns undefined using nullish coalescing operator.
This would also work
const arr: string[] = Platform.select({
ios: ["a", "b", "c"],
android: ["a", "b", "c"]
}) ?? []
Solution 2:[2]
This may suffice:
const arr: string[] = Platform.select({
ios: ["a", "b", "c"],
android: ["a", "b", "c"]
}) as unknown as string[]
But, I would be cautious. It's usually better to listen to Typescript and adjust your design accordingly.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Amila Senadheera |
| Solution 2 | lmonninger |
