#tuple in conditional function argument

18 messages · Page 1 of 1 (latest)

fallen grove
#

See playground. Presumably typescript is having trouble understanding the argument is meant to be a tuple and not an array. But how can I adjust the typing of the function (ideally) or the function-call (secondarily), to make the example pass?

bright ravenBOT
#
zaceno#7945

Preview:ts function foo<T>( arg: T extends [number, string] ? [3, "foo"] : never ) {} foo([3, "foo"]) //should be ok but isn't

fallen grove
#

(obviously this is a simplified example. I don't really need the conditional here, but I need it for the real thing)

silk dew
#

It's not a tuple vs. an array thing:

foo([3, 'foo'] as [3, 'foo']) // same error
fallen grove
#

ah hmm. then what could it be?

silk dew
#

Not sure, I still think trying to infer through conditional types is kind of dark magic.

fallen grove
#

Yeah I feel ya. Working on types (improved types actually) for a plain-js lib that builds a lot on recursion an getting it right is like layers and layers of conditional types. ... 😓

#

recursion and tuples

silk dew
#

Honestly, showing something closer to your real use-case may be useful.

fallen grove
#

You think? It would be a lot of code. I'll try to work something up not too horrible

silk dew
#

Yeah, something simple but that actually needs the conditional types to function would be helpful.

fallen grove
#

Ok here's a bigger example. Closer to the real thing:

bright ravenBOT
#
zaceno#7945

Preview:ts // - An action is a function that takes the current state, possibly a // second argument (payload), and returns a desired new state. // // - dispatch takes an action, and uses it to calculates a new state // from the current state // // - a second argument can be given to dispatch, which will be passed ...

fallen grove
#

Added comments to explain what's going on

fallen grove
#

Ok thanks for looking at this @silk dew but I figured it out I think. The original problem can be fixed like this:

bright ravenBOT
#
zaceno#7945

Preview:ts type Valid<T> = T extends readonly [number, string] ? readonly [3, "foo"] : never function foo<T>(arg: T & Valid<T>) {} ...

fallen grove
#

Actually the "as const" is redundant:

bright ravenBOT
#
zaceno#7945

Preview:ts type Valid<T> = T extends readonly [number, string] ? readonly [3, "foo"] : never function foo<T>(arg: T & Valid<T>) {} foo([3, "foo"]) //should be ok but isn't