Infer literal types for string concatenations and similar expressions
See original GitHub issueTypeScript Version: 2.1.5
Expected behavior:
const foo = 'world'; // value type: 'world'
const bar = `hello ${foo}`; // value type: 'hello world'
Actual behavior:
const foo = 'world'; // value type: 'world'
const bar = `hello ${foo}`; // type: 'string'
Motivation
For constants which are created from other constants the IntelliSense is often more useful, when we see its value type instead of the “real” type.
More practical example:
const fooBreakpoint = '800px';
const fooMediaQuery = `@media(min-width: ${fooBreakpoint})`;
When fooMediaQuery
is used I’d like to see @media(min-width: 800px)
as its type instead of string
.
Issue Analytics
- State:
- Created 7 years ago
- Reactions:17
- Comments:10 (5 by maintainers)
Top Results From Across the Web
Documentation - Template Literal Types - TypeScript
When used with concrete literal types, a template literal produces a new string literal type by concatenating the contents.
Read more >Is there currently anyway to concatenate two or more string ...
Template string types provide the ability to concatenate literal strings, convert literals of non-string primitive types to their string representation, and ...
Read more >PEP 586 – Literal Types - Python Enhancement Proposals
This PEP proposes adding Literal types to the PEP 484 ecosystem. Literal types indicate that some expression has literally a specific value.
Read more >I need to learn about TypeScript Template Literal Types
TypeScript 4.1 can concatenate strings in types using the same syntax from JavaScript: type World = "world"; type Greeting = `hello ...
Read more >Addition of string (or template) literal types should result in a ...
The templates are probably the "similar expressions", but the title also mentions "literal types for string concatenations" (also in several ...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
Worth noting that if you add
as const
this should work now with template literal types!https://www.typescriptlang.org/play?#code/MYewdgzgLgBAZiEMC8MDkB3EAnANgEzQG4YB6UmANwENcBXAUxigE8AHBgLnSz0IChQkWACNq2FDAAGACwa5cSACQBvBCAC+UmNQgwh0Iv3IxTpgHoB+IA
I’d like to be able to do something like this, building a key using string literals:
Adding a cast after the string concatenation makes the error go away, but doesn’t actually check that my key generation is still valid if I change Obj.