IlikedCPlusPlus
IlikedCPlusPlus

Reputation: 57

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.

Upvotes: 1

Views: 1127

Answers (2)

Asadullo Akramov
Asadullo Akramov

Reputation: 351

Since you assign c${string} to variable a1 which is type of Animal you got error. (Because type 'c${string}' is not assignable to type 'Animal'.) I mean any string that starts with 'c' is not assignable to string "cat"

If you annotate the type or do a1_end's type is "at", then your script works in TypeScript

Solutions:

  1. The most simple way declare a1_end with const
  const a1_end  = "at"

With above solution you could assign easily type "at" to a1_end

If you want to keep declaring variable with let, just foloow second solution

  1. Assign type of "at" into a1_end
  let a1_end : "at" = "at"

or

let a1_end  = "at" as "at"

For more information to learn type aliases in TypeScript I recommend reading this article https://www.digitalocean.com/community/tutorials/typescript-type-alias

Upvotes: 1

tenshi
tenshi

Reputation: 26322

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

Upvotes: 2

Related Questions