The team is now working on the WordPress Interactivity API. This unblocks the same UX Frontity framework enabled but directly in WordPress Core, fully compatible with the new Site Editor.
type Type1Input = {
type1input: string;
};
type Type2Input = {
type2input: string;
};
type Type1Output = {
type1output: string;
};
type Type2Output = {
type2output: string;
};
I also have a function that receives one param that can be of any of the two input types, and depending on the type of the param, the type of the return value should be one of the two output types. Something like:
This example works, but I want only one function, so I tried:
const final = <T extends Type1Input | Type2Input>(
obj: T
): T extends Type1Input ? Type1Output : Type2Output => {
if (obj.hasOwnProperty("type1input"))
return { type1output: "" };
return { type2output: "" };
};
And even though the behaviour of the function is as expected:
// This works!
const { type1output } = final({ type1input: "" });
// This doesn't work! "Property 'type2output' does not exist on type 'Type1Output'"
const { type1output } = final({ type2input: "" });
When the function is defined it can’t understand that the return value can only be one type in each case, and shows the following errors in the returns:
Type '{ type1output: string; }' is not assignable to type 'T extends Type1Input ? Type1Output : Type2Output'
Type '{ type2output: string; }' is not assignable to type 'T extends Type1Input ? Type1Output : Type2Output'.
So, I’m looking for a way to implement this function without TypeScript complaining. Any ideas?