Home > Enterprise >  typescript converting Object.entries reduced derived string array to literal types
typescript converting Object.entries reduced derived string array to literal types

Time:11-26

const program = {
  morgning: ['breakfast', 'mingle'],
  evning: ['mingle', 'eat', 'party']
} as const

const namespaceEvent = Object.entries(program).reduce(
  (acc, [namespace, events]) => [...acc, ...events.map(event => `${namespace}.${event}`)],
  [] as string[]
) // can't do 'as const' here;

type Namespace = typeof namespaceEvent[number] // sees the type as 'string' and not "morgning.breakfast" | "morgning.mingle" | "evning.mingle" | "evning.eat" | "evning.party"

const test: Namespace = 'foo.bar' // would like this to error

console.log(namespaceEvent) // ["morgning.breakfast", "morgning.mingle", "evning.mingle", "evning.eat", "evning.party"] 

How do I make this work and why doesn't it work?

CodePudding user response:

I think this is an approach to solve this:

A lot more convoluted than what I thought, there may be a better approach!

const program = {
  morgning: ['breakfast', 'mingle'],
  evning: ['mingle', 'eat', 'party']
} as const

type KV = {[K in keyof typeof program]: `${K}.${typeof program[K][number]}`};
type NS = KV[keyof KV];
// type NS = "morgning.breakfast" | "morgning.mingle" | "evning.mingle" | "evning.eat" | "evning.party"

const namespaceEvent = Object.entries(program).reduce(
  (acc, [namespace, events]) => [...acc, ...events.map(event => `${namespace}.${event}`)] as NS[],
  [] as NS[]
) 


const test: NS = 'foo.bar' // ERROR: Type '"foo.bar"' is not assignable to type 'NS'.
const test1: NS = 'morgning.breakfast' // works


console.log(namespaceEvent) // ["morgning.breakfast", "morgning.mingle", "evning.mingle", "evning.eat", "evning.party"] 

See TS Playground: https://tsplay.dev/WJRV5W

  • Related