Union and Literal Types
Part of the TypeScript course
Some values are not one thing. A function that looks up a user either finds one or does not. A form field holds either a number the user typed or nothing yet. A request is either pending, or successful, or failed, and never anything else.
The types you have written so far cannot say any of that. string means every possible string. number means every possible number. There is no way to say "one of these two types" and no way to say "this exact value and no other". Both gaps are filled by the same idea, which is the most useful thing in TypeScript that has no equivalent in most other languages. ...
Want to learn TypeScript Union and Literal Types in a real environment?
Click below, get a fresh Linux box with TypeScript ready to go, and work through Union and Literal Types hands-on with an AI tutor that knows your code.
Start this lessonUnion and Literal TypesWhat you'll learn
- Union types
- String literal types
- Numeric literal types
- Literal narrowing with as const
- Union of object shapes
Read this lesson in your language
All lessons in this course
18 lessons- 1Hello, TypeScript20 min
- 2Type Basics25 min
- 3Arrays and Tuples25 min
- 4Object Types and Interfaces25 min
- 5Functions25 min
- 6Union and Literal Types25 min
- 7Type Narrowing30 min
- 8Type Aliases vs Interfaces20 min
- 9Optional, Readonly, and Nullable25 min
- 10Enums20 min
- 11Generics30 min
- 12Classes25 min
- 13Inheritance and Abstract Classes25 min
- 14Modules25 min
- 15Utility Types30 min
- 16Mapped and Conditional Types30 min
- 17Declaration Files and Libraries25 min
- 18tsconfig and the Compiler30 min
