我想顺序比较两个元组中的类型,并返回包含0和1的元组来表示匹配类型和非匹配类型。
T1的长度匹配。码
type Equals<X, Y> = [X] extends [Y] ? [Y] extends [X] ? true : false : false;
type TupleElementComparison<T1 extends readonly unknown[], T2 extends readonly unknown[]> =
{[K in keyof T1]: Equals<T1[K], T2[K]> extends true ? 1 : 0}示例用法
type example1 = TupleElementComparison<[string, number], [string, number]>
// [1, 1]
type example2 = TupleElementComparison<[string, number], [string, number, Function]>
// [1, 1]
type example4 = TupleElementComparison<[string, number, boolean, number, Function, string], [number, boolean, string, string, Function, number]>
// [0, 0, 0, 0, 1, 0]
type example3 = TupleElementComparison<[string, number, boolean, number, Function, string], [string, number, boolean, number]>
// [1, 1, 1, 1, 0, 0]问题
TupleElementComparison实际上输出了预期的结果--当您在操场上按下结果类型时--但是我在用K访问T2时遇到了无法修复的错误
Type 'K' cannot be used to index type 'T2'.
有办法纠正这个错误吗?
发布于 2021-11-21 17:40:33
是的,有个办法。您需要向TS保证K代表keyof T2。
type TupleElementComparison<T1 extends readonly unknown[], T2 extends readonly unknown[]> =
{[K in keyof T1]: Equals<T1[K], T2[K & keyof T2]> extends true ? 1 : 0}https://stackoverflow.com/questions/70056039
复制相似问题