首页 > 解决方案 > 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 游乐场中出现关于重载签名与实现不匹配且来自调用的错误。

标签: arraystypescript

解决方案


如果使用联合类型,则必须列出该联合类型中所有可能的参数类型。如果你说

接受字符串函数或对象的函数(我可以为此使用重载),但它也接受像这样的混合值数组

您可以为可以是字符串、函数或对象的单个值定义类型别名

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 中的对象。为了能够禁止数字而不是对象,您必须更具体地了解应该接受的对象的确切类型。


推荐阅读