Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

depth protection and loose union #342

Open
xxleyi opened this issue Sep 24, 2023 · 0 comments
Open

depth protection and loose union #342

xxleyi opened this issue Sep 24, 2023 · 0 comments

Comments

@xxleyi
Copy link
Owner

xxleyi commented Sep 24, 2023

interface Nothing {

}

type Union<T, U> = T | (U & Nothing)


// Depth protection!
type LimitDepth<
  T,
  TLength = 12,
  TDepth extends any[] = []
> = TDepth['length'] extends TLength
  ? never
  : T extends object
  ? {
      [K in keyof T]: LimitDepth<T[K], TLength, [any, ...TDepth]>
    }
  : T extends Array<infer U>
  ? Array<LimitDepth<U, TLength, [any, ...TDepth]>>
  : T


type StringableKey<T> =
    T extends readonly unknown[]
        ? number extends T['length']
            ? number : `${number}`
        : string | number;

type Path0<T> =
  T extends object
    ? {
        [P in keyof T & StringableKey<T>]: `${P}` | `${P}.${Path<T[P]>}`;
      }[keyof T & StringableKey<T>]
    : never;

type Path<T> = Path0<LimitDepth<T>>;


type Foo = {
  foo: Foo
  bar: ['a', 'b']
  car: {a: {b: string}}[]
  car1: {a: {b: string}}[]

  car11: {a: {b: string}}[]

  car111: {a: {b: string}}[]

  car1111: {a: {b: string}}[]

  car11111: {a: {b: string}}[]

  car111111: {a: {b: string}}[]

  car2: {a: {b: string}}[]

  car22: {a: {b: string}}[]
  car222: {a: {b: string}}[]
  car2222: {a: {b: string}}[]
  car22222: {a: {b: string}}[]
  car3: {a: {b: string}}[]
  car4: {a: {b: string}}[]
  car6: {a: {b: string}}[]
  car7: {a: {b: string}}[]
  car8: {a: {b: string}}[]
  car9: {a: {b: string}}[]
  car0: {a: {b: string}}[]
  car00: {a: {b: string}}[]

}
const aa: Union<Path<Foo>, string> = ''


type Bar = {
  bar: ['a', 'b']
  car: {a: {b: string}}[]
}

const bb: Path<Bar> = 'car.0.a.b'

type UnionPathString = Union<Path<Foo>, string>

function test<T = {}>(a: Union<Path<T>, string>): any {
  return 99 + a;
}


test<Bar>('bar.0.3')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant