I recall seeing a feature in TypeScript where a type could be composed of another type's properties as well as it's own. But I'm not sure if I'm remembering it correctly. Consider the following:
// type or interface
type X = {
a: number
};
// type or interface
// composes properties from X ???
type XPlus = {
[P: keyof X], // include properties from X
b: boolean // add a new property
};
// instance includes properties from both X and XPlus
const instance: XPlus = {
a: 100,
b: false
};
This seems to work, but I'm not sure it's doing what I think it is. Does such a feature exist, and if so, what's it called?
You can just use an intersection type
// type or interface
type X = {
a: number
};
type XPlus = X & {
b: boolean // add a new property
};
// instance includes properties from both X and XPlus
const instance: XPlus = {
a: 100,
b: false
};
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