[英]Typescript: how to map array of types to distinct arguments via advanced types?
Current API当前 API
type Array1 = [MyArgs , MyExample] // assuming types `MyArgs` and `MyExample` exist
type Array2 = [MyExample, MyArgs ]
type ValidArray = Array1 | Array2 | ... // assuming no validArray like [MyArgs, MyArgs] and [MyExample, MyExample]
const f = (va: ValidArray) => {...}
const myargs : MyArgs = ...
const myexample : MyExample = ...
f([myargs,myexample])
Instead of what you see in the last row of the current API, I want this API:而不是你在当前 API 的最后一行看到的,我想要这个 API:
f(myargs,myexample)
without losing the information, that the 2 arguments together have to be one of the type of the enumerated arrays in ValidArrays在不丢失信息的情况下,2 个 arguments 必须是 ValidArrays 中枚举的 arrays 的类型之一
So, for example I don't want to accept these as valid argument lists:因此,例如,我不想接受这些作为有效的参数列表:
f(myargs ,myargs )
f(myexample,myexample)
I assume there is an advanced typescript technique to map (or spread?) the arrays of types to the argument list like that, but I couldn't find it out.我假设有一个先进的 typescript 技术到 map (或传播?)arrays 类型的参数列表,但我找不到它。
If I understood your question (and additional comment) correctly, const fn = (...args: [...ValidArray, ...any[]]) =>...
should be what you want.如果我正确理解了您的问题(和其他评论),
const fn = (...args: [...ValidArray, ...any[]]) =>...
应该是您想要的。 ( Playground link ) ( 游乐场链接)
type Arr1 = [1, 2]
type Arr2 = ["A", "B"]
type ValidArray = Arr1 | Arr2
const fn = (...args: [...ValidArray, ...any[]]): number => args.length
// These work
const test1 = fn(1, 2)
const test2 = fn("A", "B")
const test3 = fn("A", "B", "and", "other", "args")
// Type errors
const fail1 = fn(1, "B")
const fail2 = fn("A", 2)
const fail3 = fn(1, 1, "and", "other", "args")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.