Typescript 函数采用一个或一组对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35749833/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Typescript function taking one or array of objects
提问by Tomas
We are using simple function declaration quite a lot where function takes either single object or array of objects of some type.
我们经常使用简单的函数声明,其中函数接受单个对象或某种类型的对象数组。
Simple declaration is:
简单的声明是:
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);
}
}
But TypeScript throws "type is not assignable" error.
但是 TypeScript 会抛出“类型不可分配”错误。
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.
有没有更好的方法来做到这一点?显然我们可以有两个独立的函数,但我认为以这种方式处理单个和多个函数非常好。
回答by isvforall
You can make it easier
你可以让它更容易
addNames(names: ISomeInterface | ISomeInterface[]): void {
this.names = this.names.concat(names);
}
From MDN
来自MDN
The concat() method returns a new array comprised of the array on which it is called joined with the array(s) and/or value(s)provided as arguments.
concat() 方法返回一个新数组,该数组由调用它的数组与作为参数提供的数组和/或值连接而成。
回答by Silvermind
You could also use the rest parameter:
您还可以使用 rest 参数:
interface ISomeInterface {
name: string;
}
class SomeClass {
public names: ISomeInterface[] = []; // create an instance if applicable.
addNames(...names: ISomeInterface[]): void {
// the names argument will always be an array
this.names = this.names.concat(names);
}
}
You can call it like:
你可以这样称呼它:
addNames(name1); // just pass one
addNames(name1, name2, name3); // pass more comma separated
addNames(...[name1, name2, name3]); // pass an array.
Please note that I removed the function
keyword, because otherwise the this
keyword inside the body block might lose scope depending on who's calling it.
请注意,我删除了function
关键字,否则this
body 块内的关键字可能会失去作用域,具体取决于调用它的人。
回答by Martin
I think this is what you want
我想这就是你想要的
interface ISomeInterface {
name: string;
}
class SomeClass {
public names: ISomeInterface[];
addNames(names: ISomeInterface | ISomeInterface[]): void {
names = (names instanceof Array) ? names : [names];
this.names = this.names.concat(<ISomeInterface[]>names)
}
}
You want to use instanceOf
, not isArray.
您想使用instanceOf
,而不是 isArray。
回答by Marie
The official way typescript handles this is with multiple function signatures, for example:
官方的打字稿处理方式是使用多个函数签名,例如:
addNames(names: ISomeInterface): void;
addNames(names: ISomeInterface[]): void;
addNames(names: any): void {
...
}
You can see more information in the official handbook here
您可以在此处查看官方手册中的更多信息