Skip to content
Omni Academy
Search courses and lessons
Search
Courses
Backend Development
9
Databases
1
Frontend Development
5
Data Science
5
All courses →
Playground
HTML & CSS
JavaScript
TypeScript
Python
PHP
Ruby
Light
Dark
Auto
Sign in
Get started
All
Backend Development
Databases
Frontend Development
Data Science
Playground
Blog
HTML
JS
TS
PY
PHP
RB
← Courses
📄
Narrowing and generics
Run as I type
Reset
▶
Run
Ctrl
↵
TS
TypeScript source code
// A discriminated union: the `kind` field is what lets the compiler // tell the members apart. type Result = | { kind: 'ok'; value: number } | { kind: 'error'; message: string }; function describe(result: Result): string { // Inside each branch the type is narrowed, so .value and .message // are both safe - and reaching for the wrong one is an error. switch (result.kind) { case 'ok': return `Got ${result.value}`; case 'error': return `Failed: ${result.message}`; } } console.log(describe({ kind: 'ok', value: 42 })); console.log(describe({ kind: 'error', message: 'nope' })); // A generic that keeps the element type all the way through. function first<T>(items: readonly T[]): T | undefined { return items[0]; } const name = first(['Aisha', 'Kenji']); // string | undefined const score = first([92, 78]); // number | undefined console.log(name?.toUpperCase(), score?.toFixed(1)); // strictNullChecks is on, so this is an error rather than a crash: // console.log(name.toUpperCase()); const lengths = ['one', 'three', 'five'].map((s) => s.length); console.log('Lengths:', lengths);
Output
Rendered by your browser