I would like to create a generic interface with properties that represent a union of properties from other interfaces.
Let's say I have two interfaces
interface A {
something: string;
somethingElse: number;
}
interface B {
something: Array<string>;
}
I do not want to write interface C
as
interface C {
something: string | Array<string>;
somethingElse?: number;
}
because that would mean that whenever I modify either of the interfaces A
or B
, I would need to manually modify interface C
as well.
From what I've seen in the TypeScript documentation as well as answers here on Stack Overflow, I should declare a new type
type unionOfKeys = keyof A | keyof B;
and implement generic interface form
interface GenericInterface {
<T>(arg: T): T;
}
I was thinking in the direction of
interface C {
<T extends unionOfKeys>(arg: T): T extends unionOfKeys ? A[T] | B[T] : any
}
but that fails because of mismatch between a number of properties and their types.
I would appreciate any sort of help. Thank you.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…