Typescript 版本:5.1.6
以下是对我的问题的最小重建:
我有一个函数f
,它将接受C
的数组,其中
declare class C<a = unknown, b = unknown> {
getA(): a;
getB(): b;
};
C
的第一个泛型,也就是A,将是一个对象.
我希望explicitly
将C
的数组作为f
的元组
declare function f<T extends any[]>(arr: [...T]): any;
declare const a: C<{ name: string }, []>;
declare const b: C<{ name: string }, []>;
f([a, b])
在f
上徘徊,我们可以准确地看到我们想要的东西.
function f<[C<{
name: string;
}, []>, C<{
name: string;
}, []>]>(arr: [C<{
name: string;
}, []>, C<{
name: string;
}, []>]): any
当我想用另一个类型包装数组类型时,问题出现了,该类型将判断T
上是否有重复的键.
当我做这样的事情时:
type ExtractObject<I> = I extends C<infer P> ? P : never;
type ExtractObjectFromList<I> = {
[P in keyof I]: ExtractObject<I[P]>;
};
declare function f<T extends any[]>(arr: HasDuplicateKey<ExtractObjectFromList<[...T]>> extends true ? "Err" : T): any;
declare const a: C<{ name: string }, []>;
declare const b: C<{ name: string }, []>;
f([a, b])
或
declare function f<T extends any[]>(arr: [...T] extends infer P ? HasDuplicateKey<ExtractObjectFromList<P>> extends true ? "err" : P: never): any;
declare const a: C<{ name: string }, []>;
declare const b: C<{ name: string }, []>;
f([a, b])
it is not w或king c或rectly since it is losing the tuple type and it is converted to (C<{ name: string }, []>[])[]
我想知道是否有解决这个问题的方法,而不是在传递数组时使用as const
,这是库的一部分,我想要向后压缩.
So the idea is to highlight to display an err或 message when the keys of the first generic in C
has a collision and also ability to do some m或e checks on top of that
还有,这是HasDuplicateKey
型的
exp或t type HasDuplicateKey<T> = T extends readonly [infer First, ...infer Rest]
? Rest extends readonly [infer Next, ...infer Others]
? keyof First extends keyof Next
? true
: HasDuplicateKey<readonly [First, ...Others]>
: false
: false;