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.
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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…