TypeScript中混合类型的数组

时间:2018-06-11 07:07:09

标签: 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游戏中遇到了关于重载签名不匹配实现和来自调用的错误。

1 个答案:

答案 0 :(得分:1)

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

  

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

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

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

相关问题