I am trying to implement a function sendCommand
that returns a value of type specified by the union InputActions
, selected based on the action_id
type. Below is my code snippet:
interface OutputAction1 {
command: 'start',
params: string;
}
interface OutputAction2 {
command: 'end'
data: string;
}
type OutputActions = OutputAction1 | OutputAction2;
interface InputAction1 {
action_id: 'start',
token: string
}
interface InputAction2 {
action_id: 'end',
userData: string
}
type InputActions = InputAction1 | InputAction2;
const sendCommand = (action: OutputActions): Extract<InputActions, {action_id: OutputActions['command']}> => {
return action.command === 'start' ? {
action_id: 'start',
token: '123'
}:{
action_id: 'end',
userData: '123'
}
}
let k = sendCommand({command: 'start', params: ''})
k.token // Property 'token' does not exist on type 'InputAction2'
I expect variable k
to have type InputAction1
, however it currently has type InputActions
. Is there a way to inform TypeScript to infer the expected type based on the action_id
from the arguments?