#Generic parameter made optional in case of undefined

4 messages · Page 1 of 1 (latest)

proud niche
#

Let's say I have a function work that works with some inputs that are defined based on a generic type. In some use case there is no input and in that case I'd like to not require that parameter from the user of this function. As a workaround they pass undefined to the call which I find ugly and wonder if it can be improved.

atomic pastureBOT
#
pavel1269#0

Preview:```ts
...
function work<T extends object | undefined>(obj: Foo<T>, inputs: T) {
obj.setInputs(inputs);
}

class Bar1 extends Foo<{ id: number }> {}
const bar1 = new Bar1();
work(bar1, { id: 5});

class Bar2 extends Foo<undefined> {}
const bar2 = new Bar2();
work(bar2); // how do I make this work?
...```

proud niche
#

Oh, might have figured it out work "overloads"

atomic pastureBOT
#
pavel1269#0

Preview:ts ... function work<T extends object | void>( obj: Foo<T>, inputs: T ): void function work(obj: Foo<void>, inputs?: void): void function work<T extends object | void>( obj: Foo<T>, inputs: T ): void { obj.setInputs(inputs) } ...