Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: Optional Parameter in function, depending on Union Type has property

I have a union type:

type Msg = { type: 'banana', value: number[] } | { type: 'apple' };

now i would like to create a function that creates such a Fruit type, with two arguments and takes a generic for the Msg:

const createMsg = <M extends { type: string }>(type: M["type"], value?: M["value"]) => ({ type, value });

The value argument of the function should be linked to the type of value of the union type, and if it's not defined, the param should be optional. I would like to be able to call it in two ways:

createMsg('banana', [1, 2, 3]);
createMsg('apple');

All my current solutions so far forced me to provide a second argument undefined for the 'apple' union-type.

like image 927
bitrevolution Avatar asked Nov 21 '25 17:11

bitrevolution


1 Answers

You can't have conditional parameters, the most simple way to do this is to pass a Msg to createMsg:

const createMsg = (msg: Msg): Msg => (msg)

const a = createMsg({ type: "apple" })
const b = createMsg({ type: "banana", value: [1,2,3] })
like image 177
Nullndr Avatar answered Nov 24 '25 20:11

Nullndr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!