Hacker News new | ask | show | jobs
by TJSomething 2709 days ago
Shouldn't tuples in rest parameters from TypeScript 3.0 [0] fix that?

[0] https://www.typescriptlang.org/docs/handbook/release-notes/t...

1 comments

Not entirely.

For example, a function which takes a property path (in the form of an array of strings) and an object as parameters and returns the value at that path inside the object still needs overloads for every single tuple length.

  type Key = string | number | symbol;
  
  function get<T, K extends keyof T>(path: [K], obj: T): T[K];
  function get<T, K1 extends keyof T, K2 extends keyof T[K1]>(path: [K1, K2], obj: T): T[K1][K2];
  function get<T, K1 extends keyof T, K2 extends keyof T[K1], K3 extends keyof T[K1][K2]>(path: [K1, K2, K3], obj: T): T[K1][K2][K3];
  function get<T, K1 extends keyof T, K2 extends keyof T[K1], K3 extends keyof T[K1][K2], K4 extends keyof T[K1][K2][K3]>(path: [K1, K2, K3, K4], obj: T): T[K1][K2][K3][K4];
  function get(path: Key[], obj: any) {
      if (path.length === 0) {
          return obj;
      }
      const key = path[0] as Key;
      const rest = path.slice(1) as [Key];
      return get(rest, obj[key]);
  }
  
  
  interface Foo {
      foo: {
          bar: {
              baz: {
                  val: number;
              }
          }
      }
  }
  
  declare const foo: Foo;
  const num = get(["foo", "bar", "baz", "val"], foo);
In this case, num is implicitly typed as number, but if the path would be longer, you'd need to add more overloads.