Home > front end >  Typescript type aliases and string interpolation
Typescript type aliases and string interpolation

Time:01-25

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.

CodePudding user response:

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

  • Related