简体   繁体   English

Typescript:如何命名可能未定义的字符串数组?

[英]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:我在我的 React Native 应用程序中使用 Typescript 并定义了以下数组:

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[]' VsCode 在arr下划线并告诉我Type 'string[] | undefined' is not assignable to type 'string[]' Type 'string[] | undefined' is not assignable to type 'string[]' , so I changed it to Type 'string[] | undefined' is not assignable to type 'string[]' ,所以我将其更改为

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[]' VsCode 在定义中删除了arr的下划线,但是当我在我的代码中使用它时,它会在此处加下划线并说Argument of type 'string[] | undefined' is not assignable to parameter of type 'string[]' 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[] .我认为问题在于Platform.select()可能会返回undefined ,但是我在我的代码中使用arr进行需要它具有类型string[]而不是string[]的操作。 How can I modify my code to remove all these warnings?如何修改我的代码以删除所有这些警告?

You can give an empty array as the default value when Platform.select returns undefined using nullish coalescing operator .Platform.select使用nullish coalescing operator返回undefined时,您可以将空数组作为默认值。

This would also work这也可以

const arr: string[] = Platform.select({
  ios: ["a", "b", "c"],
  android: ["a", "b", "c"]
}) ?? []

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.通常最好听听 Typescript 并相应地调整您的设计。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM