Imagine I have a bunch of payload options like:
interface IOne {
type: 'One',
payload: {
name: string,
age: number
}
}
interface ITwo {
type: 'Two',
payload: string
}
declare type TBoth = IOne | ITwo;
So I can receive one of the two above as parameter. I want the typescript to be able to recognize the parameters of each type when using a switch for example.
The problem I'm having is when I'm trying to Create the object.
const value = req.body?.message; // just an example
const test: TBoth = {
type: value ? 'One' : 'Two, // <--- Now it should autocomplete/suggest the rights parameters based on this attribute.
}
I get:
Types of property 'type' are incompatible. Type '"One" | "Two"' is not assignable to type '"Two"'.
Is it possible?
const doSomething = (test: TBoth) => {
if(test.type === `One`) {
// hover the below `test` with VSCode you will see:
// (parameter) test: IOne
handleIOne(test)
} else {
// hover the below `test` with VSCode you will see:
// (parameter) test: ITwo
handleITwo(test)
}
}
See a live example