TypeScript type narrowing cheat sheet with runnable examples
Views
779
Copies
116
Likes
140
Comments
0
Copy rate
14.9%
Prompt
You are a TypeScript language expert. Produce a single .ts file that is a runnable cheat sheet of every major type-narrowing technique.
Target TypeScript version: [ts_version]
Audience: [audience]
Cover at minimum:
1. `typeof` guards for primitives
2. `instanceof` guards for classes
3. `in` operator for optional members
4. Equality narrowing (`===` literal, discriminated unions)
5. Truthiness narrowing with `NonNullable` pitfalls
6. User-defined type predicates (`x is Foo`)
7. `asserts` functions
8. `satisfies` operator for literal types
9. Exhaustiveness checks with `never`
10. Narrowing inside `.filter()` using predicates
11. Template literal types as compile-time narrowing
12. Const type parameters (TS 5.0+)
For each technique include:
- A short comment header naming the technique
- A minimal but real example
- A demonstration that unknown input is safely narrowed
Output format:
- Single compilable `narrowing-cheatsheet.ts` file
- Use `// --- N: Title ---` dividers
- Strict mode assumed; no `any`
- Finish with a `main()` that invokes each sample and `console.log`s a one-line result per sectionCustomise this prompt
Fill in 2 variables to personalise this prompt
Preview
You are a TypeScript language expert. Produce a single .ts file that is a runnable cheat sheet of every major type-narrowing technique.
Target TypeScript version: [ts_version]
Audience: [audience]
Cover at minimum:
1. `typeof` guards for primitives
2. `instanceof` guards for classes
3. `in` operator for optional members
4. Equality narrowing (`===` literal, discriminated unions)
5. Truthiness narrowing with `NonNullable` pitfalls
6. User-defined type predicates (`x is Foo`)
7. `asserts` functions
8. `satisfies` operator for literal types
9. Exhaustiveness checks with `never`
10. Narrowing inside `.filter()` using predicates
11. Template literal types as compile-time narrowing
12. Const type parameters (TS 5.0+)
For each technique include:
- A short comment header naming the technique
- A minimal but real example
- A demonstration that unknown input is safely narrowed
Output format:
- Single compilable `narrowing-cheatsheet.ts` file
- Use `// --- N: Title ---` dividers
- Strict mode assumed; no `any`
- Finish with a `main()` that invokes each sample and `console.log`s a one-line result per section