1

I am trying to create a dynamic type based on an array of objects. I can do this by defining literals as a type but ideally I want to learn how to do it without needing to manually define them.

Consider this example code

const testA = {
  name: 'a',
}

const testB = {
  name: 'b',
}

const testC = {
  name: 'c',
}

const items = [testA, testB, testC]

I can easily create the type using the example below

type possibleNames = 'a' | 'b' | 'c'

However I want to do this dynamically without having to define literals. I looked into TS documentation for and saw utility helpers like Pick and Record but I'm not entirely sure if those are correct or how to implement them if so.

  • can you include the input and the output type? – wonderflame Jun 09 '23 at 18:07
  • Are you okay using [`const` assertions](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-4.html#const-assertions) when initializing your variables? Like [this playground link](https://tsplay.dev/m3vR3N) shows? If so I could write up an answer explaining; if not, what am I missing? – jcalz Jun 09 '23 at 18:08
  • 1
    @jcalz Your playground example is perfect and exactly what I needed. Thank you! Add it as an answer and I'll +1 you – typeofandrew Jun 09 '23 at 18:16

0 Answers0