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

How can I write a generic TypeScript function that takes a mutable or immutable array as parameter

我试着写了下面的方法

它开始变得非常复杂,因为现在每个从 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 的 return 只是参数 listlist 未定义时,它将输出一个不可变数组.

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

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

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


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

可能看起来像这样:

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 情况下您的函数 returns [] 不是此元组的有效类型。

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

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

Payground


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

这段代码所做的是:

  • list 为 null 或未定义时,它 return 是一个包含零项的新数组
  • list 是一个零项数组时,它 return 是一个新的零项数组
  • list 是一个或多个项目的数组时,它 returns list.

在我看来这与 Nullish coalescing operator ??

几乎相同
list ?? []

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

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

// 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