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);
}
}
DEMO1 DEMO2
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);
You can not push A | B to A[] | B[] only when a is typeof B and arr typeof A[] because type B is missing abc attribute.
You ar able to push it when:
arr.push(a as A);
(arr as B[]).push(a as B);
(arr as B[]).push(a as A);
Sou you have to check i some way that a is B and arr is A[], and it that case apply some different logic.
Playground
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With