I'm trying to create a generic function which handles varies arrays of various types (that only share a few properties in common) and perform simple operations such as delete or add an item. How should the typing's look for such a function?
interface A {
value: number;
aasdsad?: number;
abc: string;
}
interface B {
value: number;
asdsad1?: string;
}
export class Main {
public getOneOfTheArrays(): A[] | B[] {
return []; // return A[] or B[] depending on certain conditions
}
public getValue(index: number) {
const arr: A[] | B[] = this.getOneOfTheArrays();
const a = this.copy(arr[index]);
a.value = 1234;
arr.push(a); // <- typing's error here
}
public copy(obj: A | B): A | B {
return Object.assign({}, obj);
}
}
Error: arr.push(a) -> Argument of type 'A | B' is not assignable to parameter of type 'A & B'.
Type 'B' is not assignable to type 'A & B'.
Property 'abc' is missing in type 'B' but required in type 'A'.
Solution so far: (arr as typeof a[]).push(a);