【发布时间】:2018-06-11 07:07:09
【问题描述】:
我有想要添加类型的现有 API,并且我有接受字符串函数或对象的函数(我可以为此使用重载),但它也接受像这样的混合值数组。
TypeScript 中是否可以包含字符串、函数或普通对象的数组?它应该为其他类型的数组抛出错误。
EDIT 基于我添加的 cmets:
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 游乐场中出现有关重载签名与实现不匹配且来自调用的错误。
【问题讨论】:
-
是的,有可能:
(string | Function | object)[] -
或
string[] | Function[] | object[]
标签: arrays typescript