#Limitation of type system with unions and generics?

1 messages · Page 1 of 1 (latest)

lusty nest
#

I ran into what feels to be a limitation of type checking.
I Have the following code:


type CallbackState = "state1" | "state2";
type CallbackType<T> =
  T extends "state1" ? { value: string } :
  T extends "state2" ? boolean : 
  never;

function setIrrigationSequenceState<T extends CallbackState>(
  state: T,
  callback: (res: CallbackType<T>) => void
) {
  if (state === "state1") {
    callback({
      value: "test",
    });
  }
}``` 
and I get the error `Argument of type '{ ok: true; value: null; }' is not assignable to parameter of type 'CallbackType<T>'.`
Theoretically typescript knows that T is type test, which would narrows 'CallbackType<T>' to  (res: { value: string }) => void, for which the given value of `callback` is valid.
Is this just too much for the type system to handle?
#

Limitation of type system with unions and generics?

tardy light
#

it'll work if you pack the args into a discriminated union:

cunning waspBOT
#
mkantor#0

Preview:```ts
type IrrigationSequenceStateArgs =
| ["state1", (res: {value: string}) => void]
| ["state2", (res: boolean) => void]

function setIrrigationSequenceState(
...[state, callback]: IrrigationSequenceStateArgs
) {
if (state === "state1") {
callback({
value: "test"
...```

lusty nest
#

even better in my case

type IrrigationSequenceStateArgs<T extends boolean, C> = [
  sequenceID: Irrigation.SequenceID,
  state: T,
  wsCallback: (res: WsResponse<C>) => void,
];

function setIrrigationSequenceState(
  ...[sequenceID, state, callback]:
    | IrrigationSequenceStateArgs<true, string>
    | IrrigationSequenceStateArgs<false, void>
) {
  if (state) {
    callback({
      ok: true,
      value: "test",
    });
  }
}```
#

Avoids deduping the args except for the depedant values.

untold bridge
#

!close feel free to reopen btw, just cleaning up the list of open threads

cunning waspBOT
#

@lusty nest
Because your issue seemed to be resolved, this post was marked as resolved by @untold bridge.
If your issue is not resolved, you can reopen this post by running !reopen.
If you have a different question, make a new post in #1057653400046674112.