arrays - TypeScript 中混合类型的数组
问题描述
我有现有的 API,我想向其中添加类型,并且我有接受字符串函数或对象的函数(我可以为此使用重载),但它也接受像这样的混合值数组。
TypeScript 中是否可以包含字符串、函数或普通对象的数组?它应该为其他类型的数组抛出错误。
根据我添加的评论进行编辑:
function Terminal(interpreter: (string, object) => void, settings: object);
function Terminal(interpreter: (string | ((string, object) => void) | object)[], settings: object) {
if (typeof interpreter == 'function') {
interpreter("foo", {});
} else if (interpreter instanceof Array) {
interpreter.forEach((arg) => console.log(arg));
}
}
Terminal(["foo", function (command, term) { }], {});
Terminal(function(command) {
}, {});
但在 TypeScript 游乐场中出现关于重载签名与实现不匹配且来自调用的错误。
解决方案
如果使用联合类型,则必须列出该联合类型中所有可能的参数类型。如果你说
接受字符串函数或对象的函数(我可以为此使用重载),但它也接受像这样的混合值数组
您可以为可以是字符串、函数或对象的单个值定义类型别名
type SingleArg = string | object | ((string, object) => void);
并定义一个接受一个 SingleArg 或数组的函数(您不需要任何重载)
function Terminal(interpreter: SingleArg | SingleArg[], settings: object) {
if (typeof interpreter == 'function') {
interpreter("foo", {});
} else if (interpreter instanceof Array) {
interpreter.forEach((arg) => console.log(arg));
}
}
Terminal(["foo", function (command, term) { }], {});
Terminal(function(command) {
}, {});
另一个限制
它应该为其他类型的数组抛出错误。
很棘手,因为例如数字是 TypeScript 中的对象。为了能够禁止数字而不是对象,您必须更具体地了解应该接受的对象的确切类型。
推荐阅读
- operating-system - 使用 Xen HYPERVISOR_console_io 超级调用
- phantomjs - 浏览器如何在 http1 上打开 6 个并行连接?
- excel - “对象'_Global'的方法'Rows'失败”启动时登录错误
- java - Swagger:如何记录仅由拦截器/过滤器使用且未出现在方法签名中的 HTTP 标头参数
- three.js - Threejs GLSL中的cameraPosition是什么?
- spotfire - 拆分行并等分对应的值
- node.js - Node js Web App的最佳数据库和简单的数据结构
- angular - Angular 6 cache.addAll() 不适用于 zonejs
- javascript - 反应本机时错误不受支持的顶级事件类型“topTouchStart”
- ocaml - 通过返回一些东西来停止函数