Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bcherny/30ebc3bc67fbbb5b4d29676f632739f9 to your computer and use it in GitHub Desktop.
Save bcherny/30ebc3bc67fbbb5b4d29676f632739f9 to your computer and use it in GitHub Desktop.

Proposal: Mirrored syntax at the type and value-levels

Motivation

Make it easier to express the operations we work with most often:

  • When modeling GraphQL types with Flow: Looking up the type of a field in a nested object type, where every field along the way is nullable and optional
  • When authoring React components: Looking up the type of a prop on another component that we compose, to directly expose it on our component too

Proposed Features

  • Lookup types: A[B]
  • Function call types: F(A)
// Objects
type A = {
  B?: {
    C?: number
  }
}
type C1 = A.B?.C            // number | undefined
type C2 = A['B']?.['C']     // number | undefined

// Arrays
type D = [number, string[]]
type E = D[1]               // string[]

// Functions
type F = number => boolean
type G1 = F(number)         // boolean
type G2 = F(3)              // boolean
type G3 = F(...[number])    // boolean

// Overloaded Functions
type H = (number, number => boolean)
       & (number, string => number)
type I = H(number, number)  // boolean
type J = H(number, string)  // number

Currently:

// Objects
type A = {
  B?: {
    C?: number
  }
}
type C = $ElementType<
  $NonMaybeType<
    $ElementType<A, 'B'>
  >,
  'C'
>                                  // number | undefined

// Arrays
type D = [number, string[]]
type E = $PropertyType<D, 1>       // string[]

// Functions
type ReturnType = <A>(() => A) => A
type F = number => boolean
type G1 = $Call<ReturnType, F>     // boolean
type G2 = $Call<ReturnType, 3>     // boolean
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment