Skip to content

Instantly share code, notes, and snippets.

@wallergoble
Created May 17, 2022 16:56
Show Gist options
  • Save wallergoble/54944e2d7985fa6dfb22cdb55a9a1a1f to your computer and use it in GitHub Desktop.
Save wallergoble/54944e2d7985fa6dfb22cdb55a9a1a1f to your computer and use it in GitHub Desktop.
Typescript Conditionals
import { options } from './lib'
/**
* Conditional Types in typescript are a subtype of generic types
*
* They are useful for deriving information from the type system
*/
// Generics aka Parametric Types: Types which take types and return other types
namespace FrontendCoeRules {
// generic reminder
type Predicate<T> = (arg: T) => boolean
let isEven: Predicate<number> = x => x % 2 === -0
// What if I want to extract number from that type?
type ReturnType<Func> = Func extends (...args: any[]) => infer R ? R : never
type IsEvenArg = ReturnType<typeof isEven>
// ReturnType already exists
type ArrayKind<T extends any[]> = T extends (infer U)[] ? U : never;
type Options = ArrayKind<typeof options>
}
// lib.ts
export let options: { label: string, value: string }[] = [{ label: 'cool stuff', value: 'actualEvil' }]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment