带一个或一组对象的Typescript函数 [英] Typescript function taking one or array of objects

查看:30
本文介绍了带一个或一组对象的Typescript函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们大量使用了简单的函数声明,其中函数采用单个对象或某种类型的对象数组.

We are using simple function declaration quite a lot where function takes either single object or array of objects of some type.

简单的声明是:

interface ISomeInterface {
    name: string;
}

class SomeClass {
    public names: ISomeInterface[] = [];

    public addNames(names: ISomeInterface | ISomeInterface[]): void {
        names = (!Array.isArray(names)) ? [names] : names;
        this.names = this.names.concat(names);
    }    
}

但是TypeScript抛出类型不可分配"错误.

But TypeScript throws "type is not assignable" error.

有更好的方法吗?显然,我们可以有两个单独的函数,但是我认为以这种方式处理单个或多个函数是很好的.

Is there better way of doing this? Obviously we could have two separate functions, but I think handling single vs multiple this way is quite fine.

推荐答案

您可以轻松完成

 addNames(names: ISomeInterface | ISomeInterface[]): void {
        this.names = this.names.concat(names);
 } 

来自 MDN

concat()方法返回一个新数组,该数组由调用该数组的数组和/或作为参数提供的 value 组成.

这篇关于带一个或一组对象的Typescript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆