#Creating tuple types from constants

8 messages · Page 1 of 1 (latest)

sudden fjord
#

Hello TS family,

Is it possible to create a tuple type from a constant? Ex:

const objTuple = [
  {
    name: 'name1',
    value: 10
  },
  {
    name: 'name2',
    value: 4
  }
];


// How to generate this tuple type automatically by detecting the type of the 'value' property and number of elements in objTuple
type TTuple = [number, number];
#

Another example that should work:

const objTuple = [
  {
    name: 'name1',
    value: { name: 'nested_name1' }
  },
  {
    name: 'name2',
    value: false
  },
  {
    name: 'name3',
    value: 'hello world!'
  }
];


// How to generate this tuple type automatically by detecting the type of the 'value' property and number of elements in objTuple
type TTuple = [{ name: string }, boolean, string];

vernal egret
#

is this what you want?

surreal thunderBOT
#
type MakeTTuple<T extends readonly { value: unknown }[]> = {
  [K in keyof T]: T[K]['value']
}

const objTuple1 = [
  {
    name: 'name1',
    value: 10
  },
  {
    name: 'name2',
    value: 4
  }
] as const;

type TTuple1 = MakeTTuple<typeof objTuple1>
//   ^? - type TTuple1 = readonly [10, 4]

const objTuple2 = [
  {
    name: 'name1',
    value: { name: 'nested_name1' }
  },
  {
    name: 'name2',
    value: false
  },
  {
    name: 'name3',
    value: 'hello world!'
  }
] as const;

type TTuple2 = MakeTTuple<typeof objTuple2>
//   ^? - type TTuple2 = readonly [{
//       readonly name: "nested_name1";
//   }, false, "hello world!"]
stray fulcrum
#
const objTuple = [
  {
    name: 'name1',
    value: 10 as number
  },
  {
    name: 'name2',
    value: 4 as number
  },
  {
    name: 'name3',
    value: 'hey' as string
  }
] as const;

type MapValues<T> = { [K in keyof T]: T[K] extends { value: infer U } ? U : never };

type X = MapValues<typeof objTuple>

Something like this also works...

#

But the need to cast to number/string is ugly

vernal egret
#

yeah, i wasn't sure if narrower types would be a feature or a bug. if you need output like [number, number] specifically (instead of readonly [10, 4]) let me know. i/somebody can probably offer other suggestions (though we might need more context)

vital barn
#

another option if you dont want the object fields to be narrowed but you do want the array to be narrowed into a tuple is to define the objects first, then define the array as const