Template Literal Type checking Template Literals

Viewed 210

I'm curious if the following is possible with the new Template Literal support in typescript 4.1:

export type LogDateType = `${number}.${number}.${number}` | `${number}.${number}` | `${number}`

I've found this works if I'm type checking a string like 2002 or 2002.5.12 but fails when type checking something like:

`${fourDigitYear}`

with the error Type 'string' is not assignable to type 'LogDateType'.

Is there a way to have this work outside of checking plain strings?

1 Answers

Issues: #41732 and #41631

assert it as const

export type LogDateType = `${number}.${number}.${number}` | `${number}.${number}` | `${number}`

const fourDigitYear = "2000";

const foo: LogDateType = `${fourDigitYear}` as const;
Related