我可以缩小数组的并集吗?

huangapple go评论123阅读模式
英文:

Can I narrow a union of arrays?

问题

我有一个类似这样的联合类型:

type MyUnion = string[] | number[];


所以它总是一个数组,要么是字符串,要么是数字。

我想知道我正在处理的数组是字符串数组还是数字数组。但是类型缩小似乎不起作用:

const arr: string[] | number[] = [];
if (typeof arr[0] === "string") {
// arr 仍然具有类型 (string[] | number[])
}


那么,如何将 `arr` 的类型缩小为联合类型中的一个类型呢?

播放区链接: https://www.typescriptlang.org/play?#code/FAMwrgdgxgLglgewgAhgUwM4wGKQBQCGATkQFzJZFwQDmA2gLrIA+yEYAtgEZpGMCU5AG4I4AE2ABvYMlnI4IZHhgBPAA5oEi4nwAMTALxHkAIkrUaJ-smly7yHTLkBfYK6A


<details>
<summary>英文:</summary>

I have a union which looks something like this:

type MyUnion = string[] | number[];


So it&#39;s always an array, of either strings or numbers.

I&#39;d like to know if the array I&#39;m dealing with is an array of strings or an array of numbers. But type narrowing doesn&#39;t seem to work:

const arr: string[] | number[] = [];
if (typeof arr[0] === "string") {
// arr has the type (string[] | number[])
}


So how can I type narrow `arr` to one of the union&#39;s types?

Playground: https://www.typescriptlang.org/play?#code/FAMwrgdgxgLglgewgAhgUwM4wGKQBQCGATkQFzJZFwQDmA2gLrIA+yEYAtgEZpGMCU5AG4I4AE2ABvYMlnI4IZHhgBPAA5oEi4nwAMTALxHkAIkrUaJ-smly7yHTLkBfYK6A

</details>


# 答案1
**得分**: 2

你可以使用类型守卫。

```javascript
function isStringArray(arr: string[] | number[]): arr is string[] {
  return typeof arr[0] === "string";
}

const arr: string[] | number[] = [];

if (isStringArray(arr)) {
  // arr 是 string[] 类型
} else {
  // arr 是 number[] 类型
}
英文:

You can use type guards.

function isStringArray(arr: string[] | number[]): arr is string[] {
  return typeof arr[0] === &quot;string&quot;;
}

const arr: string[] | number[] = [];

if (isStringArray(arr)) {
  // arr is type string[]
} else {
  // arr is type number[]
}

答案2

得分: 1

你可以使用typeguard来实现这一点:

export function isStringArray(array: string[] | number[]): array is string[] {
  return typeof array[0] === "string";
}

或者你可以以通用的方式检查任何数组是否为字符串数组:

export function isStringArray<T>(array: T[]): array is string[] {
  return array.every(element => typeof element === "string");
}

然后根据你的代码:

if (isStringArray(arr)) {
  // arr 的类型是 string[]
}
英文:

You can use typeguard to achieve that:

export function isStringArray(array: string[] | number[]): array is string[] {
  return typeof array[0] === &quot;string&quot;;
}

or you can do it generic way to check if any array is a string array

export function isStringArray&lt;T&gt;(array: T[]): array is string[] {
  return array.every(element =&gt; typeof element === &quot;string&quot;);
}

then based on your code

if (isStringArray(arr)) {
  // arr has type string[]
}

huangapple
  • 本文由 发表于 2023年3月8日 18:38:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/75671954.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定