Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typescript type aliases and string interpolation

I’ve been using Typescript for a while and am currently working with type aliases which have the following form:

type Animal = "cat" | "dog";
let a1_end = "at";
let a1: Animal = `c${a1_end}`

As far as I understood, only the values "cat" or "dog" would be allowed for any variable of the type Animal. But strictly speaking, it should be possible since the result would be "cat", right? I’m just asking since I get the error that the only allowed values for any variable of the type Animal can be either "cat" or "dog" when I’m running this code.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The problem is that a1_end‘s type is inferred to be string.

let a1_end = "at";
//  ^? string

So the use of a string literal here actually produces a type that can’t be assigned to "cat":

let a1: Animal = `c${a1_end}`
//               ~~~~~~~~~~~~ type is `c${string}`

and since `c${string}` is not assignable to "cat", you get an error (because any string that starts with "c" is not assignable to the string "cat").

If you annotate the type or tell TypeScript in any way that a1_end‘s type is "at", it works:

let a1_end = "at" as "at";
let a1_end = "at" as const;
let a1_end: "at" = "at";
const a1_end = "at";

Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading