0

Is there a way in Typescript to convert union member to string?

Like following:

type T = TObjectA | TObjectB

// use somewhere as string literal union:

type TAsString = "TObjectA" | "TObjectB"

Simplified example of actual intent:

import type { user, address, invoice } from "@/db-codegen"

type TModel =  user | address | invoice

type MyProps = {
    model: TModel
    // This obviously wont't work. So as .toString() and other naive attempts
    modelName: `${TModel}`
    // desired outcome: "user" | "address" | "invoice"
}

This is probably a duplicate of TypeScript: Getting names (as string) of Union's possible types?, but it has only one – and not really satisfactory – answer.

I was hoping this thread String Union to string Array could help, but it probably addresses a slightly different problem.

Thanks a lot.

BZKN
  • 1,499
  • 2
  • 10
  • 25
HynekS
  • 2,738
  • 1
  • 19
  • 34
  • 1
    Chances are, what you need is a discriminated union: otherwise your `MyProps` type can technically have `user` in `model`, yet have `modelName` of "address". There is no 1-to-1 relation between `model` and `modelName` in your type. – Terry Jan 24 '22 at 09:54
  • @Terry You're right ,I didn't think of that. Thank you. – HynekS Jan 24 '22 at 10:04
  • The question that you've linked is probably the way you want to do going forward: a discriminated union. – Terry Jan 24 '22 at 10:08
  • The issue I see is that I can't leverage the autogenerated types from db. The only option I see is to add a 'name' column to all the tables, to have it accessible in TS, which is… meh :/. – HynekS Jan 24 '22 at 10:12

0 Answers0