Skip to content

Instantly share code, notes, and snippets.

@ahrjarrett
Last active September 20, 2022 19:16
Show Gist options
  • Select an option

  • Save ahrjarrett/0a8b4d65b3fbfa208997228150212d7a to your computer and use it in GitHub Desktop.

Select an option

Save ahrjarrett/0a8b4d65b3fbfa208997228150212d7a to your computer and use it in GitHub Desktop.
/**
* Recursive "find and replace".
*
* TODO: Treat tuples differently than arrays so we don't
* lose type information when replacing, e.g.:
* ```
* S extends [UnsafeAny] ? // ...
* S extends [UnsafeAny, UnsafeAny] ? // ...
* ```
*/
export type Replace<S, A, B>
= S extends A | Primitive
? S extends A
? B | Exclude<S, A>
: S
: S extends AnyArr ? Replace<S[number], A, B>[]
: { [K in keyof S]: Replace<S[K], A, B> }
// Example util you could build with it
export type CorrectOpenAPINullables<A> = Replace<A, null, undefined>
export type Nil = null | undefined
export type Scalar = number | string | boolean | bigint
export type Primitive = Nil | Scalar
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment