"a" | "b" Literal Types

Last updated: 2026-10-22

"a" | "b" Literal Types

Literal types promote a value into a type: "up", 1 and true are all types. Alone they are niche, but combined into unions they pin down exact allowed values.

GroupType Composition
KindType
Strict modeNot required

ℹ️ Info The editor transpiles TypeScript to JavaScript and runs it (no type checking); see each example's Output for type-check results.

📝 Syntax

type Size = "small" | "medium" | "large";
let size: Size = "medium";

const mode = "dark"; // const infers the literal type "dark"
let level = 3;       // let infers the widened number

⚙️ Parameters

"a" | 42 | trueThree primitive literal kinds work as types: "a", 42, true
as constLocks object/array members to literal types — handy for config constants

Returns:None — literal types are type-level only and disappear after compilation.

▶ Example

Edit the code below and click Try it to see the transpiled result:

Output:

up x2 right x1

(Runtime output after transpilation; move("Up", 1) is a compile error — literals must match exactly, case-sensitively)

💡 Notes

ℹ️ Info let widens to string; const keeps the literal type ("dark") — the most common way literal types arise.
💡 Tip Add as const to config constants: every member becomes a literal type, ready to feed literal-union parameters.
⚠️ Note Literal matching is exact and case-sensitive: "Up" does not fit "up", and neither does extra whitespace.
More cases coming soon.

📚 Related tutorials

❓ FAQ

Q Why does const yield a literal type while let yields string?
A A const never changes, so TS keeps the most precise "value as type"; a let may receive other strings, so it widens to string. Narrow it with an annotation or as const when needed.
Q What does as const do?
A It asserts the deepest readonly form: members become literal types and non-writable. { method: "GET" } infers { method: string }; with as const, method is exactly "GET".
Q Literal unions vs enums?
A Literal unions cost nothing at runtime and interoperate with plain strings; enums add a namespace and reverse mapping. Literal unions suffice for most value domains (see the enum entry).
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏