tl; dr:我要强烈键入以下内容。
const foo = [ 'a' ] as const;
const bar = [ 1 ] as const;
const baz = [ true ] as const;
const concatted = foo.concat(bar, baz);
type Concatted = typeof concatted; // expect ['a', 1, true]
我已经想出了如何为0..n参数添加定义,但是我想对任意数量的对象进行添加,最好使用一个或两个定义。
假设我有:
const strArray = [ 'a' ] as const;
const numArray = [ 1 ] as const;
const concatenated = strArray.concat(numArray);
我们知道级联等于['a', 1]
。我已经弄清楚了如何为此编写类型定义concat()
。
declare global {
interface ReadonlyArray<T> {
concat<
A extends ReadonlyArray<T>,
I extends ReadonlyArray<unknown>
>(this: A, items: C): [...A, ...I];
}
}
type Concatenated = typeof concatenated; // => ['a', 1]
但是,JavaScriptArray.concat()
接受任意数量的数组。所以现在开始
const strArray = [ 'a' ] as const;
const numArray = [ 1 ] as const;
const boolArray = [ true ] as const;
const concatenated = strArray.concat(numArray, boolArray); // => [ 'a', 1, true ]
在TypeScript 4的可变参数元组之前,解决方案类似于
declare global {
interface ReadonlyArray<T> {
concat<
A extends ReadonlyArray<T>,
I extends ReadonlyArray<unknown>
>(this: A, items: I): [...A, ...I];
concat<
A extends ReadonlyArray<T>,
I1 extends ReadonlyArray<unknown>,
I2 extends ReadonlyArray<unknown>
>(this: A, item1: I1, item2: I2): [...A, ...I1, ...I2];
// ...additional concat() definitions through I_n...
}
}
我希望有了TypeScript 4,我可以做些更简单的事情
declare global {
interface ReadonlyArray<T> {
concat<
A extends ReadonlyArray<T>,
I extends ReadonlyArray<ReadonlyArray<unknown>>
>(this: A, ...items: I): [...A, ...(...I)];
}
}
这显然行不通。我猜有一些黑魔法使用
((val: ReadonlyArray<ReadonlyArray<unknown>>) => void) extends ((val: [infer U, ...infer R]) => void)
? [...U, ...<something something recurse with R>]
: never
模式,我从来没有使用得到的窍门,也许在串联与魔法Extract<>
所看到的这个答案。
如果类型可以在没有任何魔术的情况下进行递归,那将非常好。然后我可以轻松地写:
type Concat<T extends ReadonlyArray<ReadonlyArray<unknown>>> =
T extends [ReadonlyArray<unknown>, ...infer U]
? [...T[0], ...Concat<U>]
: [];
interface ReadonlyArray<T> {
concat<
A extends ReadonlyArray<T>,
I extends ReadonlyArray<ReadonlyArray<unknown>>
>(this: A, ...items: I): [...A, ...Concat<I>];
}
顺便说一句,我从来不理解为什么不支持递归类型(只要它们在n个深度之内即可解析)。无限递归当然是不好的/不可能的,但是我认为可以很容易/有效地为大小为100或小于100的元组支持此语法。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句