When looking at the code provided below,
function system(): ISavable & ISerializable {
return {
num: 1, // error!
save() {},
load() {},
serialize() {},
deserialize() {},
}
}
interface ISavable {
save: () => void
load: () => void
}
interface ISerializable {
seriailze: () => void
deserialize: () => void
}
The Issue
There is an error in returning property num: 1
as TypeScript indicates it is not specified by either ISavable
or ISerializable
.
To address this, one potential solution could involve creating an additional type that encompasses all the elements the function will return but I am exploring a way to maintain flexibility for unique properties within the function.
To clarify further, when you do not define the return of your function explicitly, its type is inferred and you benefit from autocomplete suggestions. I desire this functionality along with the ability to infer types and ensure specific properties are included in the return value.
Query
I am interested in typing the return of my function in such a manner where it mandates the inclusion of properties from both interfaces (ISavable
and ISerializable
) while still permitting the addition of extra custom properties relevant to the function.
With that in mind,
- Is this achievable?
- If so, how can it be done?
Although classes might fulfill my requirements, I am specifically seeking a solution tailored for functions.