microsoft / microsoft/TypeScript
If all values used in a template literal have a literal type, then the template should have a literal type
まだ誰も着手していません。
- 主要言語
- Go
- スター
- 111k
- フォーク
- 14.4k
- 平均マージ
- 1日 19時間
- マージ済み PR(30日)
- 117
説明
Search Terms
template string, string literal, template string literal, cast template string as literal
Suggestion
It seems all template strings are widened to type string; however, when all the variables used inside a template string have literal types, it would be nice if the resulting string also had a literal type.
Use Cases
I maintain a library, and I'd like it if templated strings for CSS properties like box shadow would show up for my dev users in intellisense, instead of just "string".
Here's a screenshot showing the current behavior:

It would be very useful if readonly boxShadow and readonly border had literal types instead of a generic string type, to inform my devs what value is passed.
Examples
const elementColors = {
...
globalFocus: '#ff0000',
...
} as const
const widths = {
...
default: 4,
...
} as const
const shadow = {
default: {
boxShadow: boxShadow: `${ elementColors.globalFocus } 0 0 0 ${ width.default }px`,
},
...
} as const
In the above, typeof elementColors.globalFocus === '#ff0000' and typeof width.default === 4, but typeof shadow.default.boxShadow === string. All of the parts used to create the template have literal types, so why doesn't the resulting string have a literal type? TypeScript should be able to infer that only a single possible value is valid for this. typeof shadow.default.boxShadow should equal '#ff0000 0 0 0 4px'.
Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- could be breaking for people who rely on templates having type string vs a literal type
- 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.
コントリビューションガイド
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
調査の方向性
まず、リテラル値の補間を使った例を再現し、shadow.default.boxShadow の推論された型を要求されたリテラルと比較します。すべての部分がリテラル型であるテンプレートリテラルが、対応する完全一致の文字列リテラルとして推論され、既存の実行時の動作が変わらなければ完了です。
索引モデルが issue の本文から書いたものです。
評価
- 技術スタック
- typescript
- 領域
- compilers
- issue の種類
- 機能追加
- 難易度
- 5/5
- 見積もり時間
- 1週間以上
- 活発さ
- 停滞
- 明瞭さ
- 明確に書かれている
- 初心者へのやさしさ
- 35/100