Skip to content

Instantly share code, notes, and snippets.

@nwellis
Created April 18, 2025 12:03
Show Gist options
  • Save nwellis/a401a6915d1518c5142cfb74632bc9d9 to your computer and use it in GitHub Desktop.
Save nwellis/a401a6915d1518c5142cfb74632bc9d9 to your computer and use it in GitHub Desktop.
Infer type from field
export function withType<TElement extends { __type: string }, TType extends TElement["__type"]>(
elements: TElement[],
type: TType
): Extract<TElement, { __type: TType }>[] {
return elements?.filter(element => element.__type === type) as Extract<TElement, { __type: TType }>[]
}
export function withoutType<TElement extends { __type: string }, TType extends TElement["__type"]>(
elements: TElement[],
type: TType
): Exclude<TElement, { __type: TType }>[] {
return elements?.filter(element => element.__type !== type) as Exclude<TElement, { __type: TType }>[]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment