首页 > 解决方案 > 如何声明一个始终为空的 Typescript 数组?

问题描述

我在模块内声明一个私有默认值。该值是一个空数组。它总是空的,因为它是一种备用值。TS 希望我输入数组,但似乎我不应该声明数组将保存什么样的值,因为这个函数被许多调用者使用,每个调用者都处理不同类型的数据。

我有这样的事情:

const DATA_FOR_ERROR_CASES = []

export default function unpackData( packedData: string|undefined ) {
  if(packedData === undefined) {
    // return a Node-style callback tuple
    return [
      new TypeError('missing packedData'),
      DATA_FOR_ERROR_CASES.slice()
    ]
  }
  /*
    Otherwise, do really complex stuff, which can generate an
    array OR a hash, depending on the string content of packedData
  */
  return [
    undefined, // as in Node, error arg is undefined in success case
    unpackedData
  ]
}

我使用一个空数组作为我的默认返回,因为实验表明这将允许调用者乐观地解构它,无论他们在成功案例中是否期望哈希或列表。像这样:

// one caller knows it'll get a hash (if things don't break)
let [ error, { name, address } ] = unpackData(packedContact)

// another caller expects an actual list
let [ error, [ firstChoice, secondChoice, ...otherChoices ] ] = unpackData(packedPrefs)

如果解包失败,第一个元素将是一些有用的 Error 实例,第二个值将是DATA_FOR_ERROR_CASES.

在错误情况下,如果DATA_FOR_ERROR_CASES是散列,则第二个示例会失败,因为您不能在 POJO 上使用数组解构。您可以对数组使用数组解构和属性解构。我希望调用者能够乐观地解构,而不必这样做:

// this sucks because it's so awkward
let [ error, unpacked ] = unpackData(packedPrefs)
if(error) throw error // ... or bail in some other way, preventing next line

let [ firstChoice, secondChoice, ...otherChoices ] = unpacked

我的问题:我应该如何声明的类型DATA_FOR_ERROR_CASES

TS 不会接受这个:

const DATA_FOR_ERROR_CASES: Array = []
// Generic type 'Array<T>' requires 1 type argument(s). ts(2314)

标签: javascriptarraystypescript

解决方案


推荐阅读