27862-medium-cartesianproduct

Back

type CartesianProduct<T, U> = T extends T ? U extends U ? [T, U] : never : never;

Solution by wendao-liu #35148

// Union<2 | 3> -> [2] | [3]
type UnionToArr<T> = T extends infer R ? [R] : never
// [1, ...Union<2 | 3>] -> [1, 2] | [1, 3]
type CartesianProduct<T, U> = T extends infer R ? [R, ...UnionToArr<U>] : never

Solution by ouzexi #34154

type CartesianProduct<T, U> =
  T extends T
    ? U extends U
      ? [T, U]
      : never
    : never

Solution by drylint #34136

can not handle CartesianProduct<'a', Function | string>, ['a', Function] | ['a', string]>

type CartesianProduct<T extends PropertyKey, U extends PropertyKey> = {
  [P1 in T]: {
    [P2 in U]: [P1, P2];
  }[U];
}[T];

Solution by sunupupup #33486

type CartesianProduct<T, U> = T extends T ? U extends U ? [T, U] : U : T

Playground

Solution by teamchong #33001

type CartesianProduct<T, U> = T extends any
  ? U extends any
    ? [T, U]
    : never
  : never;

Solution by Vampirelee #32583

type CartesianProduct<T, U> =
  T extends T
    ? U extends U
      ? [T, U]
      : never
    : never

Solution by milletlovemouse #30995

// your answers

type FromUnionToArrUnion<U> = U extends U ? [U] : never

type CartesianProduct<T, U> = [...FromUnionToArrUnion<T>, ...FromUnionToArrUnion<U>]

Solution by kerolossamir165 #30411

type CartesianProduct<T, U> = T extends T ? U extends U ? [T,U] | CartesianProduct<T,Exclude<U,U>> : never : never;

Solution by idebbarh #30172

type CartesianProduct<T, U> = T extends T
  ? U extends U
    ? [T, U]
    : never
  : never;

Solution by DoubleWoodLin #28920

根据联合类型的遍历规则,遍历时会进行循环,因此这里相当于两层 for 循环遍历即可

type CartesianProduct<T, U> = T extends T
  ? U extends U
    ? [T, U]
    : never
  : never

Solution by linjunc #28554

type UnionToArray<T> = T extends T ? [T] : never;
type CartesianProduct<T, U> = [...UnionToArray<T>, ...UnionToArray<U>]; //利用数组展开自动分发

// old way
// type CartesianProduct<T, U, _UU = U> = T extends T ? _UU extends U ? [T, _UU] | CartesianProduct<T, Exclude<U, _UU>> : never : never;

Solution by E-uler #28120

type CartesianProduct<T, U> = T extends any
  ? U extends any
    ? [T, U]
    : never
  : never

Solution by XkSuperCool #28015

type CartesianProduct<T, U> = T extends infer A
  ? U extends infer B
    ? [A, B]
    : never
  : never;

Solution by JohnLi1999 #27941

type CartesianProduct<T, U,TC = T,UC = U> = 
TC extends T?
  UC extends U?
    [TC,UC]
    :never
  :never

Solution by jiangshanmeta #27907