gpt4 book ai didi

arrays - typescript :数组类型取决于先前的数组元素

转载 作者:行者123 更新时间:2023-12-05 04:55:37 25 4
gpt4 key购买 nike

是否可以在 Typescript 中实现一个无限数组(不是元组),其类型取决于数组的前一个元素?

下面是一些伪 typescript 代码来举个例子:

class B<T, U> {}

function foo<X, Y>(...args: [B<X, Z0>, B<Z0, Z1>, B<Z1, Z2>, ..., B<ZN, Y>]) {}

foo<string, number>(new B<string, number>, new B<number, boolean>, new B<boolean, number>); // Correct
foo<string, number>(new B<string, number, new B<number, boolean>); // Incorrect
foo<string, number>(new B<string, number>, new B<boolean, number>); // Incorrect

我应该用什么替换“[B<X, Z0>, B<Z0, Z1>, B<Z1, Z2>, ..., B<ZN, Y>]”才能使这项工作正常进行?这可能吗?

谢谢!

最佳答案

我最近遇到了类似的问题。我的问题涉及创建一长串流。流 i 的输出必须是流 i+1 的输入,等等。我是这样解决的:

type OmitFirst<T extends any[]> = T extends [any, ...infer R] ? R : never
type GetValueOrDefault<Thing, Key, Default = never> = Key extends keyof Thing ? Thing[Key] : Default
type Pipe<Start, Finish, Inputs extends [Start, ...any[]], Outputs extends any[] = OmitFirst<Inputs>> = {
[I in keyof Inputs]: DuplexConstructor<Inputs[I], GetValueOrDefault<Outputs, I, Finish>>
}

export function pipe<F, L, P extends [F, ...any[]]>(
...streams: [ReadableConstructor<F>, ...Pipe<F, L, P>, WritableConstructor<L>]
): Writable {
const source = streams[0]
const duplexes = streams.slice(1, -1) as Pipe<F, L, P>
const sink = streams[streams.length - 1] as WritableConstructor<L>

let tail = readable(source)
duplexes.forEach((dp) => (tail = tail.pipe(duplex(dp))))
return tail.pipe(writable(sink))
}

关于arrays - typescript :数组类型取决于先前的数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65373216/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com