【问题标题】:Array for mixed types in TypeScriptTypeScript 中混合类型的数组
【发布时间】: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 游乐场中出现有关重载签名与实现不匹配且来自调用的错误。

【问题讨论】:

标签: arrays typescript


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

【讨论】:

    猜你喜欢
    • 2021-12-15
    • 2022-10-12
    • 1970-01-01
    • 2014-04-28
    • 1970-01-01
    • 2017-05-07
    • 1970-01-01
    • 2021-12-02
    • 1970-01-01
    相关资源
    最近更新 更多