Skip to content

Instantly share code, notes, and snippets.

@Kcko
Created February 7, 2025 14:42
Show Gist options
  • Save Kcko/3f6f71c3bfd31a68be1c91ed9ece1cb6 to your computer and use it in GitHub Desktop.
Save Kcko/3f6f71c3bfd31a68be1c91ed9ece1cb6 to your computer and use it in GitHub Desktop.
/*
Extract je utility typ v TypeScriptu, který umožňuje vytvořit nový typ extrahováním (vybráním) hodnot, které jsou společné mezi dvěma typy. Funguje jako opak Exclude, protože místo odstranění hodnot vybírá ty, které se shodují. Syntaxe vypadá takto:
Extract<T, U>
*/
// 1
type Status = 'active' | 'inactive' | 'pending' | 'deleted';
type ActiveStatus = Extract<Status, 'active' | 'pending'>;
let status1: ActiveStatus = 'active'; // OK
let status2: ActiveStatus = 'pending'; // OK
let status3: ActiveStatus = 'inactive'; // Error: Type '"inactive"' is not assignable to type 'ActiveStatus'.
// 2
type Numeric = number | string | boolean;
type OnlyString = Extract<Numeric, string>;
const value1: OnlyString = 'Hello'; // OK
const value2: OnlyString = 42; // Error: Type 'number' is not assignable to type 'OnlyString'.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment