Reputation: 641
I'd like to build a generic interface so that it can extend the allowed value types of a given interface. I try to illustrate this below....
If I have an interface as below...
interface Original {
prop1: string
prop2: number
}
How can I build a generic interface, let's say ExtraValueTypes<T> so that the result is as below?
type ExtraType = myType
interface WithExtraValueTypes {
prop1: string | myType
prop2: number | myType
}
such that...
ExtraValueTypes<Original> = WithExtraValueTypes
Upvotes: 1
Views: 33
Reputation: 10790
You can make use of mapped types as below. All you need to a map definition that unions all the properties with Extra type.
interface Original {
prop1: string
prop2: number
}
type Extra = { a: string }
type Extrator<T> ={
[P in keyof T] : T[P] | Extra
}
type ExtraOriginal = Extrator<Original>;
const sample: ExtraOriginal ={
prop1: { a: "foo" },
prop2 :3
}
const sample2: ExtraOriginal ={
prop1: "foo",
prop2 :{a:"bar"}
}
Upvotes: 3