Home > Net >  Get certain value from returned multi-type array
Get certain value from returned multi-type array

Time:09-12

I have a function/hook which returns an array with types boolean and MyErrorType

export declare const getErrorData: () => readonly [ boolean, MyErrorType ];

In some scenarios I am only interested in the 2nd value of the array of type MyErrorType and I was wondering if there is a clean way to get this? Currently only solution I could get to work is just fetching the 2nd element in the array i.e.

const error = getErrorData()[1];

Is there any way to fetch the element of the array based on the type of the variable? something like

const error: MyErrorType = getErrorData();

CodePudding user response:

You can't change the behavior of a program based on types, because the idea of Typescript is that types will be erased and only the resulting Javascript will be run.

You could return an object instead of an array as @tymzap suggests, another solution is to use destructuring:

const [, error] = getErrorData();

CodePudding user response:

It definitely does not answer your question, but seemed like a good challenge to create a type that iterates over an array and returns the index of an expected type. Its pure type definition, here you go:

Typescript playground link

Short edition:

type GrabIndexOfType<
  T,
  A extends any[] | readonly any[],
  Curr extends number = A["length"],
  Idx extends number = 0,
> = Curr extends 1
  ? A[0] extends T 
    ? Idx
    : never
  : A extends [any, ... infer Rest] | readonly [any, ... infer Rest]
    ? GrabIndexOfType<T, [... Rest], SubOne<Curr>, AddOne<Idx>>
    : never
;

type Tuple<N extends number, T extends any[] = []> = T["length"] extends N
  ? T
  : Tuple<N, [... T, any]>;

type AddOne<A extends number> = Tuple<A> extends [... infer U] ? [any, ... U]["length"] : never;

type SubOne<A extends number> = Tuple<A> extends [
  ...infer U,
  any
]
  ? U["length"]
  : never;

type b = GrabIndexOfType<MyErrorType, ReturnType<typeof getErrorData>>;
  • Related