type-edit
v0.1.0
Published
TypeScript type-level utility types.
Maintainers
Readme
type-edit
Type-level utilities for working with union-branched object types.
Transform operations
Import Call and the operations you need from type-edit.
import type { Call, Evolve, Narrow, Reject } from 'type-edit'Use Call<Operation, Source> to run an operation.
type Resource =
| { kind: 'user'; name: string }
| { kind: 'team'; members: number }
| { kind: 'role'; level: number }
type Source = {
a: Resource
b: Resource
c: string
}
type Changed = Call<Evolve<{
a: Narrow<{ kind: 'user' }>
b: Reject<{ kind: 'user' }>
}>, Source>
// type Changed = {
// a: { kind: 'user'; name: string }
// b:
// | { kind: 'team'; members: number }
// | { kind: 'role'; level: number }
// c: string
// }Built-in operations
Call<Operation, Source>
Evolve<ObjectSpec>
Pipe<[Operation, ...Operation[]]>
Narrow<Pattern>
Reject<Pattern>
Widen<Patch>
Where<Pattern, Operation>
Where<Not<Pattern>, Operation>
Branch<Pattern, TrueOperation, FalseOperation>Evolve
Use Evolve to apply operations to object fields while preserving unspecified fields.
type Result = Call<Evolve<{
a: Narrow<{ kind: 'user' }>
}>, Source>Where
Use Where to apply an operation only to matching union branches.
import type { Where, Widen } from 'type-edit'
type Result = Call<Where<
{ kind: 'team' },
Widen<{ selected: true }>
>, Resource>Use Not<Pattern> to select the opposite side.
import type { Not } from 'type-edit'
type Result = Call<Where<
Not<{ kind: 'user' }>,
Widen<{ selected: true }>
>, Resource>Branch
Use Branch to transform matching and non-matching branches differently.
import type { Branch } from 'type-edit'
type Result = Call<Branch<
{ kind: 'user' },
Widen<{ editable: true }>,
Widen<{ editable: false }>
>, Resource>Pipe
Use Pipe to run operations left-to-right.
import type { Pipe } from 'type-edit'
type Result = Call<Pipe<[
Widen<{ selected: true }>,
Widen<{ visible: true }>,
]>, Resource>Standalone utilities
The standalone utility forms are available from type-edit/standalone.
import type {
Narrow as StandaloneNarrow,
Reject as StandaloneReject,
Unify,
Widen as StandaloneWiden,
} from 'type-edit/standalone'Narrow<Source, Pattern>
Keeps the part of Source that matches Pattern.
type User = StandaloneNarrow<Resource, { kind: 'user' }>
// type User = { kind: 'user'; name: string }Reject<Source, Pattern>
Removes the part of Source that matches Pattern.
type NonUser = StandaloneReject<Resource, { kind: 'user' }>
// type NonUser =
// | { kind: 'team'; members: number }
// | { kind: 'role'; level: number }Widen<A, B>
Combines two types into a type that can represent both.
type State = StandaloneWiden<
{ status: 'idle'; count: number },
{ status: 'loading' }
>
// type State = { status: 'idle' | 'loading'; count: number }Unify<T>
Turns a union of object shapes into a single object shape with shared and optional properties.
Install
npm install type-edit