0

I am attempting to define a string literal type that has a variable parameter in it.

e.g:

type myStringType = 'a' | 'b' | 'c' | `d[${parameter}]`

I'd like the string d[parameter] to accept anything which resembles d[foo] or d[bar]

Edited: added back ticks to template literal, though i'm not attached to this being a template literal and if there is another solution...

humont
  • 63
  • 1
  • 6
  • Did you mean to use a template string for “d”? If so, swap the single quotes to back ticks. – evolutionxbox Oct 28 '20 at 15:05
  • That seems like job for a regular expression, unless typescript offers special syntax for such things. – Lonnie Best Oct 28 '20 at 15:08
  • 1
    I don't think you can achieve this with a union type, here's [a similar question](https://stackoverflow.com/questions/51445767/how-to-define-a-regex-matched-string-type-in-typescript) that unfortunately got a "not possible" answer. – DBS Oct 28 '20 at 15:09
  • 1
    I was hoping something new had come up. After a little extra research it seems this is coming in [typescript 4.1](https://devblogs.microsoft.com/typescript/announcing-typescript-4-1-beta/#template-literal-types) – humont Oct 28 '20 at 15:21

1 Answers1

0

Starting from Typescript 4.1, you can use template literal types.

type parameter = "foo" | "bar"

type myStringType = 'a' | 'b' | 'c' | `d[${parameter}]`

// type myStringType = "a" | "b" | "c" | "d[foo]" | "d[bar]"
Mahdi Ghajary
  • 2,717
  • 15
  • 20