英文:
Can I narrow a union of arrays?
问题
我有一个类似这样的联合类型:
type MyUnion = string[] | number[];
所以它总是一个数组,要么是字符串,要么是数字。
我想知道我正在处理的数组是字符串数组还是数字数组。但是类型缩小似乎不起作用:
const arr: string[] | number[] = [];
if (typeof arr[0] === "string") {
// arr 仍然具有类型 (string[] | number[])
}
那么,如何将 `arr` 的类型缩小为联合类型中的一个类型呢?
<details>
<summary>英文:</summary>
I have a union which looks something like this:
type MyUnion = string[] | number[];
So it's always an array, of either strings or numbers.
I'd like to know if the array I'm dealing with is an array of strings or an array of numbers. But type narrowing doesn'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'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] === "string";
}
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] === "string";
}
or you can do it generic way to check if any array is a string array
export function isStringArray<T>(array: T[]): array is string[] {
return array.every(element => typeof element === "string");
}
then based on your code
if (isStringArray(arr)) {
// arr has type string[]
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论