Skip to content

Negated types #815

Open
Open

Description

@ssalbdivad

This would allow some or all types to be negated (likely using a new ! operator). The challenge here would be integrating these checks with the type system so that intersections can still be reduced to the fullest extent possible.

If this turns out to not be feasible, we could implement it shallowly using a similar approach to narrows where we'd only check equality to determine assignability, or could potentially restrict the set of types that could be negated to literals.

More investigation required.

A couple additional notes after spending a minute thinking about this:

My intuition is that there'd be a "negated" node that could be attached to each branch node. You'd maintain it opposite the normal node- intersections would be attached as unions. It's kind of mind bending that it could essentially continue to invert but maybe the recursion would work everything out and it would be doable. All the second level negations would be intersected back up to the base type? But what if they're in branches of a union? That seems like a problem.

A couple notes based on a followup conversation:

ssalbdivad: Say you have !T. You intersect this with !U. The result could either be represented as !T & !U or !(T | U). In this case, a negated type would be a constraint like any other attached to an intersection

ssalbdivad: So in this scenario, say that T actually already had attached to it another negated type, !A.

ssalbdivad: To reduce the negation of T, you would have to intersect A (now unnegated) with the intersection !T & !U is being attached to

ssalbdivad: Is it possible this will never actually require you to use a union directly in your representation? I still have to think that through, maybe it's possible to distribute it so each negation is only ever an intersection. That would solve the problem

ssalbdivad: Maybe the key is just using !T & !U instead of !(T | U) like I was thinking initially

ssalbdivad: Yeah that makes sense because negation can always be distributed over a union

ssalbdivad: So that would never be the reduced representation anyways

ssalbdivad: You just have to make sure when you define the intersection, you define it in such a way that behaves like reducing a union

TypeHoles: Sounds about right.

ssalbdivad: So if we have the first representation

ssalbdivad: Could every second-level negated type could be directly intersected with the base intersection and pruned from the negations? So you'd only ever have one level of negation?

ssalbdivad: I think so. I think my problem is when I thought "oh yeah, intersecting negations would act like a union" I thought it had to be represented that way but it just has to be reduced that way

ssalbdivad: Oh wait no this was wrong 😞 The behavior has to act like a union because !T could be satisfied by any constraint of T not being satisfied, not just the negated ones. Intersecting !A from T back up to the base intersection as A doesn't work

ssalbdivad: This object foo thing is kind of weird with objects being the only types that can have arbitrary props so we'll change it to {a: 0, b: 1}
ssalbdivad: You could negate it as !{a: 0} | !{b: 1}
ssalbdivad: So if you intersected that with e.g. {b: 1} you could reduce the negated portion to !{ a: 0 }
ssalbdivad: If the last negated branch is ever pruned the type is unsatisfiable

Activity

  1. moved this from To do to Backlog in arktypeioon Jul 2, 2023
  2. TizzySaurus commented on Jun 13, 2024

    @TizzySaurus
    Contributor

    Commenting to note that something like type(...).not() would also be really handy for JsonSchema -> ArkType (#729), since JsonSchema has a not 'operator' which is currently non-trivial to implement into AT. As an example:

    {"not": {"type": "string"}}
  3. ssalbdivad commented on Jun 13, 2024

    @ssalbdivad
    MemberAuthor

    @TizzySaurus It is trivial to implement, you just create a predicate that negates the inner type.

    It is just not trivial to fully reduce and compare to other types, but that is not needed to translate JSON schema.

  4. nidomiro commented on Nov 19, 2026

    @nidomiro

    I'm also looking for support of not here. My usecase is in match.

    I want to match something like mongodb change stream events and therefore I need to do something like this:
    { operationType: "'insert'", fullDocument: '!null && !undefined' }.
    So basically check if fullDocument is there or not.

    Workarounds:

    import { match as arkMatch, type } from 'arktype'
    import { match as tsMatch, P } from 'ts-pattern'
    
    type ChangeEvent = {
      operationType: 'insert' | 'update' | 'delete'
      fullDocument?: object | null | undefined
    }
    
    // #1 — switch (true)
    export function matchWithSwitch(event: ChangeEvent) {
      const fullDocument = event.fullDocument
    
      switch (true) {
        case event.operationType === 'insert' && fullDocument != null:
          return fullDocument
        case event.operationType === 'update' && fullDocument != null:
          return fullDocument
        case event.operationType === 'update':
          console.info('Update event has no fullDocument; ignoring it')
          return undefined
        default:
          console.debug(`Ignoring change event of type ${event.operationType}`)
          return undefined
      }
    }
    
    // #2 — ArkType discriminator
    export const matchWithArkTypeDiscriminator = arkMatch
      .in<ChangeEvent>()
      .at('operationType')
      .match({
        "'insert'": (event) => {
          if (event.fullDocument == null) {
            console.debug(`Ignoring change event of type ${event.operationType}`)
            return undefined
          }
          return event.fullDocument
        },
        "'update'": (event) => {
          if (event.fullDocument == null) {
            console.info('Update event has no fullDocument; ignoring it')
            return undefined
          }
          return event.fullDocument
        },
        default: (event) => {
          console.debug(`Ignoring change event of type ${event.operationType}`)
          return undefined
        },
      })
    
    // #3 — ArkType nullish-first
    const nullishFullDocument = type('null | undefined').optional()
    
    export const matchWithArkTypeNullishFirst = arkMatch
      .in<ChangeEvent>()
      .case({ fullDocument: nullishFullDocument }, (event) => {
        if (event.operationType === 'update') {
          console.info('Update event has no fullDocument; ignoring it')
        } else {
          console.debug(`Ignoring change event of type ${event.operationType}`)
        }
        return undefined
      })
      .case({ operationType: "'insert'" }, (event) => event.fullDocument!)
      .case({ operationType: "'update'" }, (event) => event.fullDocument!)
      .default((event) => {
        console.debug(`Ignoring change event of type ${event.operationType}`)
        return undefined
      })
    
    // #4 — ts-pattern
    export function matchWithTsPattern(event: ChangeEvent) {
      return tsMatch(event)
        .with(
          { operationType: 'insert', fullDocument: P.not(P.nullish) },
          (event) => event.fullDocument,
        )
        .with(
          { operationType: 'update', fullDocument: P.not(P.nullish) },
          (event) => event.fullDocument,
        )
        .with({ operationType: 'update' }, () => {
          console.info('Update event has no fullDocument; ignoring it')
          return undefined
        })
        .otherwise(() => {
          console.debug(`Ignoring change event of type ${event.operationType}`)
          return undefined
        })
    }
    
    // #5 — ArkType custom non-nullish schema
    const nonNullish = type('unknown').narrow(
      (value): value is {} => value != null,
    )
    
    export const matchWithArkTypeNarrow = arkMatch
      .in<ChangeEvent>()
      .case(
        { operationType: "'insert'", fullDocument: nonNullish },
        (event) => event.fullDocument,
      )
      .case(
        { operationType: "'update'", fullDocument: nonNullish },
        (event) => event.fullDocument,
      )
      .case({ operationType: "'update'" }, () => {
        console.info('Update event has no fullDocument; ignoring it')
        return undefined
      })
      .default((event) => {
        console.debug(`Ignoring change event of type ${event.operationType}`)
        return undefined
      })
    
    // #6 — ArkType object pattern
    export const matchWithArkTypeObject = arkMatch
      .in<ChangeEvent>()
      .case(
        { operationType: "'insert'", fullDocument: 'object' },
        (event) => event.fullDocument,
      )
      .case(
        { operationType: "'update'", fullDocument: 'object' },
        (event) => event.fullDocument,
      )
      .case({ operationType: "'update'" }, () => {
        console.info('Update event has no fullDocument; ignoring it')
        return undefined
      })
      .default((event) => {
        console.debug(`Ignoring change event of type ${event.operationType}`)
        return undefined
      })

    Sorted fastest to slowest by unweighted average across the seven benchmark cases:

     ┌───┬────────────────────────────┬──────────────────────────────────────────────────────────────┬───────────────┬─────────────────────────────┐
     │ # │ Approach                   │ Short form                                                   │ Approx. ops/s │ Compared with switch (true) │
     ├───┼────────────────────────────┼──────────────────────────────────────────────────────────────┼───────────────┼─────────────────────────────┤
     │ 1 │ switch (true)              │ case op === 'insert' && doc != null                          │ ~25.0M        │ Baseline                    │
     ├───┼────────────────────────────┼──────────────────────────────────────────────────────────────┼───────────────┼─────────────────────────────┤
     │ 2 │ ArkType discriminator      │ .at('operationType'); check doc != null in handler           │ ~23.3M        │ ~7% lower                   │
     ├───┼────────────────────────────┼──────────────────────────────────────────────────────────────┼───────────────┼─────────────────────────────┤
     │ 3 │ ArkType nullish-first      │ Match nullishFullDocument first; later handler uses doc!     │ ~22.8M        │ ~9% lower                   │
     ├───┼────────────────────────────┼──────────────────────────────────────────────────────────────┼───────────────┼─────────────────────────────┤
     │ 4 │ ts-pattern                 │ .with({ op: 'insert', fullDocument: P.not(P.nullish) }, ...) │ ~1.12M        │ ~22× lower                  │
     ├───┼────────────────────────────┼──────────────────────────────────────────────────────────────┼───────────────┼─────────────────────────────┤
     │ 5 │ ArkType custom non-nullish │ type('unknown').narrow(v => v != null)                       │ ~0.426M       │ ~59× lower                  │
     ├───┼────────────────────────────┼──────────────────────────────────────────────────────────────┼───────────────┼─────────────────────────────┤
     │ 6 │ ArkType object pattern     │ .case({ op: "'insert'", fullDocument: 'object' }, ...)       │ ~0.424M       │ ~59× lower                  │
     └───┴────────────────────────────┴──────────────────────────────────────────────────────────────┴───────────────┴─────────────────────────────┘

    These are rough local results averaged across the seven benchmark cases run with vitest bench.

    Versions:

    • node: 26.12.1
    • vitest: 5.1.1
    • arktype: 2.2.10
    • ts-pattern: 5.9.2

    I assume nothing will beat the switch case here, but I would like to have something that is less error-prone and faster than ts-pattern at the same time.

    If this is the wrong issue, I'm happy to create a new one.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    • Status
      Backlog

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions