Currently, I am exploring the concept of creating a versatile function that can handle arrays of various types with only a few common properties. The goal is to enable simple operations like adding or removing elements from these arrays. What would be the ideal approach for defining the typings of such a function?
interface A {
value: number;
aasdsad?: number;
abc: string;
}
interface B {
value: number;
asdsad1?: string;
}
export class Main {
public retrieveArray(): A[] | B[] {
return []; // Returns either A[] or B[] based on specific conditions
}
public getValue(index: number) {
const arr: A[] | B[] = this.retrieveArray();
const a = this.clone(arr[index]);
a.value = 1234;
arr.push(a); // <- Typing error occurs here
}
public clone(obj: A | B): A | B {
return Object.assign({}, obj);
}
}
DEMO Link 1 DEMO Link 2
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);