-
Notifications
You must be signed in to change notification settings - Fork 0
Literal Types
Jorge Castro edited this page Nov 10, 2025
·
1 revision
type Season = "spring" | "summer" | "fall" | "winter";This one works
const season1: Season = "spring";This one won't work because type '"autumn"' is not assignable to type 'Season'.
const season2: Season = "autumn";`It also works with numbers and other types
function compare(a: string, b: string): -1 | 0 | 1 {
return a === b ? 0 : a > b ? 1 : -1;
}This will show an error because method is a string.
declare function handleRequest(
url: string,
method: "GET" | "POST" | "PUT" | "DELETE"
): void;
const request = { url: "https://example.com", method: "GET" };
handleRequest(request.url, request.method);With a const assertion, it won't show the error
const request = { url: "https://example.com", method: "GET" as const };
handleRequest(request.url, request.method);- Sync-Obsidian-with-GitHub-on-iOS
- Obsidian-community-plugins
- Optimizing-Novel-Word-Count-Plugin-for-Git-Users
- What is TypeScript, and why you should use it
- Quick setup
- Inference and type annotations
- Fundamental Types
- Object Types
- Union Types
- Type Aliases and Interfaces
- Type Assertions
- Literal Types
- null and undefined
- Narrowing
- Creating Types from Types
- Common Built‐in and Utility Types
- tsc CLI ‐ (The Compiler)
- Avoid using Object or {}
- Ignoring TypeScript errors
- TypeScript resources