Skip to content

Restrict template literal interpolation expressions to strings #30239

Open
@jamietre

Description

@jamietre

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Needs ProposalThis issue needs a plan that clarifies the finer details of how it could be implemented.SuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions