javascript - 如何声明一个始终为空的 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)
解决方案
推荐阅读
- ios - iOS 10 Safari 修复了滚动后无法点击的菜单按钮
- c# - 在 C# 中使用 TCP 接收来自客户端错误的多个响应
- php - 尝试使用nodejs时没有输出
- google-apps-script - 通过 Apps 脚本检查 Google 表格单元格内容以确定是否应导出 PDF
- mysql - 关于 AWS/SQL 和 Django
- javascript - 树莓派文件不同步,?
- javascript - 如何用两个数组渲染 FlatList?
- jquery - 取消选中单击其他复选框时选中的所有复选框不起作用
- python - 干扰代码的注释块/缩进
- java - 在静态 void main 中调用方法