typescript - 我如何编写一个将可变或不可变数组作为参数的通用 TypeScript 函数

标签 typescript generics

我试着写了下面的方法。

它开始变得非常复杂,因为现在每个从 catchUndefinedList 接收结果的方法都必须能够处理可变和不可变数组。

有人能帮帮我吗?

/**
 * Catch any errors with a list.
 */
export function catchUndefinedList<T> (list: readonly T[] | T[]): readonly T[] | T[] {
  return nullOrUndefined(list) || !list?.length ? [] : list
}

编辑:添加了nullOrUndefined

export function nullOrUndefined (el: any): el is (undefined | null) {
  return typeof el === 'undefined' || el === null
}

编辑:添加了一些简单的示例来展示问题。

可以看出,catchUndefinedList 接收一个 list1 作为参数,它是一个可变数组。 在这种情况下,它会输出一个不可变数组,即使 list1 是可变的,catchUndefinedList 的返回只是参数 list列表 不是未定义的。

当尝试推送到 list2 时,它将因不可变性而失败并返回 TS2339。

const list1 = ['foo']
const list2 = catchUndefinedList(list1)
list2.push('bar')

最佳答案

首先,只有在 list 的类型中允许使用 nullundefined 时,这个问题才真正有意义。所以我假设你打算允许这样做。


听起来您希望函数的返回值是与输入相同类型的数组。这意味着您的函数需要在数组 上是通用的,而不仅仅是该数组的成员类型。这是因为数组的 readonly 特性是数组类型的一部分,而不是成员。

这可能看起来像这样:

export function catchUndefinedList<
  T extends readonly unknown[]
> (list: T | null | undefined): T {
  return (
    nullOrUndefined(list) ||
    !list?.length
      ? [] // Type 'T | never[]' is not assignable to type 'T'.
      : list
  )
}

// mutable
const list1 = ['foo']
const list2 = catchUndefinedList(list1)
list2.push('bar')

// immutable
const immlist1: readonly string[] = ['foo']
const immlist2 = catchUndefinedList(immlist1)
immlist2.push('bar') // Property 'push' does not exist on type 'readonly string[]'.(2339)

这里可以看到可变数组的push是允许的,不可变数组的push是不允许的。这很好。


但是,这确实给元组带来了问题。这就是我上面的代码片段中出现类型错误的原因。想象一下你这样调用这个函数:

const tuple2 = catchUndefinedList<[string, number, boolean]>(undefined)
tuple2[0].split('') // no type error, instead there is a runtime error

这是一个问题,因为您的函数在 undefined 情况下返回 [],这不是此元组的有效类型。

可以使用[] as unknown as T 来消除错误,但实际上并不推荐这样做。如果有人确实尝试使用元组执行此操作,您可能会在奇怪的地方遇到运行时错误。

老实说,我不确定如何正确地约束它,因为所有元组都是无界数组的子类型。

Payground


也就是说,这对于简单的 null 检查来说似乎相当复杂。您确定这是您要走的路吗?

这段代码所做的是:

  • list 为 null 或 undefined 时,它返回一个新的零项数组
  • list 是零项数组时,它返回一个新的零项数组
  • list 是一个或多个项目的数组时,它返回 list

在我看来,这实际上与 Nullish coalescing operator ?? 相同

list ?? []

您的代码与这一行之间的唯一区别是,当项目为零时,返回 list 而不是新的空数组。但它仍然是一个空数组,所以这种区别可能并不重要。

但这在上述所有情况下都表现得很好:

// mutable
const list1 = ['foo'] as string[] | undefined
const list2 = list1 ?? []
list2.push('bar')

// immutable
const immlist1 = ['foo'] as readonly string[] | undefined
const immlist2 = immlist1 ?? []
immlist2.push('bar') // type error

// tuple
const tuple1 = ['a', 1] as [string, number] | undefined
const tuple2 = tuple1 ?? []
tuple2.push('c') // type error

Playground

关于typescript - 我如何编写一个将可变或不可变数组作为参数的通用 TypeScript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70584364/

相关文章:

angular - Ionic CLI 为什么要制作模块文件?

typescript - 发布 TypeScript 包时如何处理可选的对等依赖项?

c++ - C 中的模板在 C++ 中使用 void *

typescript - 创建将为对象属性赋值的通用 TypeScript 函数

c# - 如何在 List<MyClass<object>> 中存储多个泛型类型?

javascript - 变量在通过 fetch 分配之前使用

visual-studio - VSCode : how to scroll through IntelliSense overload signature suggestions

Angular 2 Observables 无法分配给 bool 值

c# - 隐藏基类的属性

java - 泛型问题java