0

I am wondering why I can do this:

let stT: `${number}%` = "5435%"

But not this:

let str: string = "5435%"
let strT: `${number}%` = str;

And also not this:

let str: string = 5435
let strT: `${number}%` = `${str}%`;

What is the relationship (if any) of string and string template? Why can I assign a template a litteral but not a string variable? Is there a way you can match and convert the string to a string template?

I found this: Convert a string to a template string But I believe it to slightly different than my question.

  • 2
    In the second case str's inferred type is just string, surely; there's absolutely no guarantee it will be a string *ending with %*. – jonrsharpe Jan 14 '21 at 22:13
  • Sorry, I forgot to include the type of str. Edit includes them now. Is there a way to match it similar to regex.match() or convert the string to the template? –  Jan 14 '21 at 22:20
  • 1
    And now in the third case the compiler errors out on the obvious mismatch between `5435` and the explicit type of `string` before reaching the string templating part. – jonrsharpe Jan 14 '21 at 22:21
  • 1
    In the third case, if you replace `let str: string` with `let str: number`, it still doesn't work. However, this was [fixed in the 4.2 beta](https://devblogs.microsoft.com/typescript/announcing-typescript-4-2-beta/#template-literal-expressions-have-template-literal-types). – Lauren Yim Jan 14 '21 at 22:22
  • @jonrsharpe that's not true. Check out [this playground](https://www.typescriptlang.org/play?#code/C4TwDgpgBAwgrgZ2AewLYGVgCcCWA7AcygF4oADAEgG885UAjCLAXwrIG4BYAKB4GNkeJFFQgAYnDx8SUABQA3AIYAbAFyxEKDNnwEAlCQB8UKjyhQsEYHCx4oS5V27MePURKmyA5AAYAjABMAMwUXnpO7pJ83v7BwQAswWER4lHeogByEADumLiEyUA). I set it up so that only Template Literal Types can be applied to the function that and on `$` – DivisionByZero Jan 14 '21 at 22:44
  • @DivisionByZero *what's* not true? That the inferred type in case 2 prior to the edit was `string`, or that the value `5435` isn't assignable to a variable with the explicit type `string` in case 3 afterwards? – jonrsharpe Jan 14 '21 at 22:45
  • @jonrsharpe I'm sorry. I think I completely misunderstood your first comment. I thought you were referring to the type declaration in the first example. – DivisionByZero Jan 14 '21 at 22:52

0 Answers0