microsoft / microsoft/TypeScript

Restrict template literal interpolation expressions to strings

Open
#30,239 46 comments 79 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Needs Proposal Suggestion
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

Search Terms

"template literal"

There are many hits, some which seem related, but everything I could find was a much bigger ask or wider in scope

Suggestion

Add a compiler option to enforce using only strings in ES6 string template literals

Use Cases

When using string literals, any variables are coerced to strings, which can lead to undesirable behavior.

As far as I can tell there's no way to avoid this behaviour. In the spirit of tying everything, I'd prefer that only actual string types are permissible for use in string templates to avoid accidental coercion by passing null, undefined or object types that may have unexpected string representations, and force users to explicitly convert them to strings.

Examples

For example:

function formatName(name: string | null): string {
   return `Name is: ${name}`;
} 

formatName(null)  === "Name is: null"

Ideally the compiler would fail since name can be null.

Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

No files, tests, or compiler entry points are named in the issue. Start by reviewing the template-literal type-checking behavior and the comment discussion, then define the option's accepted expression types, diagnostics, and test coverage before implementation.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.