Home > Net >  Typescript: how to name array of strings that could be undefined?
Typescript: how to name array of strings that could be undefined?

Time:01-26

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?

CodePudding user response:

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"]
}) ?? []

CodePudding user response:

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.

  •  Tags:  
  • Related