Home > OS >  hi , any idea how to make auto inferring a tuple?
hi , any idea how to make auto inferring a tuple?

Time:07-26

any idea how to make auto inferring a tuple ? current inference is (string|boolean)[] , the issue here is i want only one case (A) to have the array of false and string , and the others to be a Boolean values only. how to achieve this with auto inference or any other method without having to type the whole object since it is kind of long.

const inicialErrState: { [key: string]: boolean; a: [boolean, string] } = {
    a: [false, ''],
    b: false,
    c: false,
    d: false,
  }; 
  

CodePudding user response:

My suggestion would be to use a helper function which infers tuple types:

const tuple = <T extends any[]>(...t: T) => t;

const initialErrState = {
    a: tuple(false, ''),
    b: false,
    c: false,
    d: false,
};
/* const initialErrState: {
    a: [boolean, string];
    b: boolean;
    c: boolean;
    d: boolean;
} */

Playground link to code

CodePudding user response:

You can use the following type. This enforces that a is a tuple, but it allows all other values to be either a boolean or a tuple, so it's not a perfect solution. It may work well enough for your use case, though.

type InitialErrorState = {
  [key: string]: [boolean, string] | boolean
} & {
  a: [boolean, string]
};
  • Related