Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions src/system/memory/discard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,16 @@ THE SOFTWARE.

import { Metrics } from "./metrics.ts"
import { Clone } from './clone.ts'
import { IsBase } from '../../type/types/base.ts'

type ObjectLike = Record<PropertyKey, any>

/** Discards multiple property keys from the given object value */
export function Discard(value: ObjectLike, propertyKeys: PropertyKey[]): ObjectLike {
Metrics.discard += 1
const result: ObjectLike = {}
const descriptors = Object.getOwnPropertyDescriptors(Clone(value))
const clone = Clone(value)
const result: ObjectLike = IsBase(value) ? clone : {}
const descriptors = Object.getOwnPropertyDescriptors(clone)
const keysToDiscard = new Set(propertyKeys)
for (const key of Object.keys(descriptors)) {
if (keysToDiscard.has(key)) continue
Expand Down
72 changes: 72 additions & 0 deletions src/type/extends/base.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
/*--------------------------------------------------------------------------

TypeBox

The MIT License (MIT)

Copyright (c) 2017-2025 Haydn Paterson

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

---------------------------------------------------------------------------*/

// deno-fmt-ignore-file

import { type TSchema } from '../types/schema.ts'
import { type TProperties } from '../types/properties.ts'
import { type Base, IsBase } from '../types/base.ts'
import { type TExtendsRight, ExtendsRight } from './extends-right.ts'

import * as Result from './result.ts'

// ------------------------------------------------------------------
// ExtendsBase
//
// Two Base instances extend each other if they are instances of
// the same class (i.e., they have the same constructor). This
// models TypeScript's structural type checking at runtime for
// custom Base types.
//
// Note: At the type level, TypeScript cannot determine if two Base
// instances have the same constructor, so we check if they're
// mutually assignable (both ways) which indicates they're likely
// the same type.
// ------------------------------------------------------------------
export type TExtendsBase<Inferred extends TProperties, Left extends Base, Right extends TSchema> = (
Right extends Base
? [Left] extends [Right]
? [Right] extends [Left]
? Result.TExtendsTrue<Inferred>
: Result.TExtendsFalse
: Result.TExtendsFalse
: TExtendsRight<Inferred, Left, Right>
)

export function ExtendsBase<Inferred extends TProperties, Left extends Base, Right extends TSchema>
(inferred: Inferred, left: Left, right: Right):
TExtendsBase<Inferred, Left, Right> {
return (
IsBase(right)
// Use Equals method for checking equality between Base instances
? (left.Equals(right)
? Result.ExtendsTrue(inferred)
: Result.ExtendsFalse())
: ExtendsRight(inferred, left, right)
) as never
}
4 changes: 4 additions & 0 deletions src/type/extends/extends-left.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ THE SOFTWARE.
import { type TExtendsAny, ExtendsAny } from './any.ts'
import { type TExtendsArray, ExtendsArray } from './array.ts'
import { type TExtendsAsyncIterator, ExtendsAsyncIterator } from './async-iterator.ts'
import { type TExtendsBase, ExtendsBase } from './base.ts'
import { type TExtendsBigInt, ExtendsBigInt } from './bigint.ts'
import { type TExtendsBoolean, ExtendsBoolean } from './boolean.ts'
import { type TExtendsConstructor, ExtendsConstructor } from './constructor.ts'
Expand Down Expand Up @@ -60,6 +61,7 @@ import { type TExtendsVoid, ExtendsVoid } from './void.ts'
import { type TAny, IsAny } from '../types/any.ts'
import { type TArray, IsArray } from '../types/array.ts'
import { type TAsyncIterator, IsAsyncIterator } from '../types/async-iterator.ts'
import { type Base, IsBase } from '../types/base.ts'
import { type TBigInt, IsBigInt } from '../types/bigint.ts'
import { type TBoolean, IsBoolean } from '../types/boolean.ts'
import { type TConstructor, IsConstructor } from '../types/constructor.ts'
Expand Down Expand Up @@ -94,6 +96,7 @@ export type TExtendsLeft<Inferred extends TProperties, Left extends TSchema, Rig
Left extends TAny ? TExtendsAny<Inferred, Left, Right> :
Left extends TArray<infer Items extends TSchema> ? TExtendsArray<Inferred, Left, Items, Right> :
Left extends TAsyncIterator<infer Type extends TSchema> ? TExtendsAsyncIterator<Inferred, Type, Right> :
Left extends Base ? TExtendsBase<Inferred, Left, Right> :
Left extends TBigInt ? TExtendsBigInt<Inferred, Left, Right> :
Left extends TBoolean ? TExtendsBoolean<Inferred, Left, Right> :
Left extends TConstructor<infer Parameters extends TSchema[], infer InstanceType extends TSchema> ? TExtendsConstructor<Inferred, Parameters, InstanceType, Right> :
Expand Down Expand Up @@ -125,6 +128,7 @@ export function ExtendsLeft<Inferred extends TProperties, Left extends TSchema,
IsAny(left) ? ExtendsAny(inferred, left, right) :
IsArray(left) ? ExtendsArray(inferred, left, left.items, right) :
IsAsyncIterator(left) ? ExtendsAsyncIterator(inferred, left.iteratorItems, right) :
IsBase(left) ? ExtendsBase(inferred, left, right) :
IsBigInt(left) ? ExtendsBigInt(inferred, left, right) :
IsBoolean(left) ? ExtendsBoolean(inferred, left, right) :
IsConstructor(left) ? ExtendsConstructor(inferred, left.parameters, left.instanceType, right) :
Expand Down
25 changes: 25 additions & 0 deletions src/type/extends/extends-right.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import { Memory } from '../../system/memory/index.ts'
import { type TSchema, IsSchema } from '../types/schema.ts'
import { type TProperties } from '../types/properties.ts'
import { type TAny, IsAny } from '../types/any.ts'
import { type Base, IsBase } from '../types/base.ts'
import { type TEnum, type TEnumValue, IsEnum } from '../types/enum.ts'
import { type TInfer, IsInfer } from '../types/infer.ts'
import { type TIntersect, IsIntersect } from '../types/intersect.ts'
Expand Down Expand Up @@ -85,6 +86,28 @@ function ExtendsRightAny<Inferred extends TProperties, Left extends TSchema>
return Result.ExtendsTrue(inferred)
}
// ----------------------------------------------------------------------------
// ExtendsRightBase
// ----------------------------------------------------------------------------
type TExtendsRightBase<Inferred extends TProperties, Left extends TSchema, Right extends Base> = (
Left extends Base
? Left extends Right
? Result.TExtendsTrue<Inferred>
: Result.TExtendsFalse
: Result.TExtendsFalse
)
function ExtendsRightBase<Inferred extends TProperties, Left extends TSchema, Right extends Base>
(inferred: Inferred, left: Left, right: Right):
TExtendsRightBase<Inferred, Left, Right> {
return (
IsBase(left)
// Use Equals method for checking equality between Base instances
? (right.Equals(left)
? Result.ExtendsTrue(inferred)
: Result.ExtendsFalse())
: Result.ExtendsFalse()
) as never
}
// ----------------------------------------------------------------------------
// ExtendsRightEnum
// ----------------------------------------------------------------------------
type TExtendsRightEnum<Inferred extends TProperties, Left extends TSchema, Right extends TEnumValue[],
Expand Down Expand Up @@ -159,6 +182,7 @@ function ExtendsRightUnion<Inferred extends TProperties, Left extends TSchema, R
// ----------------------------------------------------------------------------
export type TExtendsRight<Inferred extends TProperties, Left extends TSchema, Right extends TSchema> = (
Right extends TAny ? TExtendsRightAny<Inferred, Left> :
Right extends Base ? TExtendsRightBase<Inferred, Left, Right> :
Right extends TEnum<infer Values extends TEnumValue[]> ? TExtendsRightEnum<Inferred, Left, Values> :
Right extends TInfer<infer Name extends string, infer Type extends TSchema> ? TExtendsRightInfer<Inferred, Name, Left, Type> :
Right extends TTemplateLiteral<infer Pattern extends string> ? TExtendsRightTemplateLiteral<Inferred, Left, Pattern> :
Expand All @@ -172,6 +196,7 @@ export function ExtendsRight<Inferred extends TProperties, Left extends TSchema,
TExtendsRight<Inferred, Left, Right> {
return (
IsAny(right) ? ExtendsRightAny(inferred, left) :
IsBase(right) ? ExtendsRightBase(inferred, left, right) :
IsEnum(right) ? ExtendsRightEnum(inferred, left, right.enum) :
IsInfer(right) ? ExtendsRightInfer(inferred, right.name, left, right.extends) :
IsIntersect(right) ? ExtendsRightIntersect(inferred, left, right.allOf) :
Expand Down
9 changes: 9 additions & 0 deletions src/type/types/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,15 @@ export class Base<Value extends unknown = unknown> implements TSchema, XGuard<Va
public Clone(): Base {
throw Error('Clone not implemented')
}
/** Checks if this type equals another instance. Override for custom equality. */
public Equals(other: unknown): other is this {
return (
other !== null &&
typeof other === 'object' &&
'constructor' in other &&
this.constructor === other.constructor
)
}
}
// ------------------------------------------------------------------
// Guard
Expand Down
40 changes: 38 additions & 2 deletions test/typebox/runtime/type/engine/action/evaluate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -806,15 +806,17 @@ Test('Should Evaluate 64', () => {
Type.Object({ value: Type.Optional(new Foo()) })
]))
Assert.IsTrue(Type.IsOptional(T.properties.value))
Assert.IsTrue(Type.IsNever(T.properties.value))
Assert.IsTrue(Type.IsBase(T.properties.value))
Assert.IsTrue(T.properties.value instanceof Foo)
})
Test('Should Evaluate 65', () => {
const T = Type.Evaluate(Type.Intersect([
Type.Object({ value: new Foo() }),
Type.Object({ value: new Foo() })
]))
Assert.IsFalse(Type.IsOptional(T.properties.value))
Assert.IsTrue(Type.IsNever(T.properties.value))
Assert.IsTrue(Type.IsBase(T.properties.value))
Assert.IsTrue(T.properties.value instanceof Foo)
})
Test('Should Evaluate 66', () => {
const T = Type.Evaluate(Type.Intersect([
Expand All @@ -825,3 +827,37 @@ Test('Should Evaluate 66', () => {
Assert.IsTrue(Type.IsBase(T.properties.value))
Assert.IsTrue(T.properties.value instanceof Foo)
})
class Bar<T extends string> extends Type.Base {
public constructor(private kind: T) {
super();
}
public override Check(value: unknown): value is unknown {
return true
}
public override Errors(value: unknown): object[] {
return []
}
public override Clone(): Bar<T> {
return new Bar(this.kind)
}
public override Equals(other: unknown): other is this {
return other instanceof Bar && other.kind === this.kind
}
}
Test('Should Evaluate 67', () => {
const T = Type.Evaluate(Type.Intersect([
Type.Object({ value: Type.Optional(new Bar('1')) }),
Type.Object({ value: Type.Optional(new Bar('1')) })
]))
Assert.IsTrue(Type.IsOptional(T.properties.value))
Assert.IsTrue(Type.IsBase(T.properties.value))
Assert.IsTrue(T.properties.value instanceof Bar)
})
Test('Should Evaluate 68', () => {
const T = Type.Evaluate(Type.Intersect([
Type.Object({ value: Type.Optional(new Bar('1')) }),
Type.Object({ value: Type.Optional(new Bar('2')) })
]))
Assert.IsTrue(Type.IsOptional(T.properties.value))
Assert.IsTrue(Type.IsNever(T.properties.value))
})
12 changes: 5 additions & 7 deletions test/typebox/runtime/type/extends/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,13 @@ export class TBase extends Type.Base<unknown> {

const Base = new TBase()
// ------------------------------------------------------------------
// Identity: Note, it's not obvious to how to handle Base checks
// without relying on nominal typing, while technically possible
// to check for the constructor, bundlers and downlevel targets
// make this a unreliable check. For now, Base is considered a
// distinct type of itself.
// Identity: Base types extend each other if they are instances
// of the same class (constructor check). This models TypeScript's
// structural type checking at runtime.
// ------------------------------------------------------------------
Test('Should Extends 0', () => {
const R: ExtendsResult.TExtendsFalse = Extends({}, Base, Base)
Assert.IsTrue(ExtendsResult.IsExtendsFalse(R))
const R: ExtendsResult.TExtendsTrue<{}> = Extends({}, Base, Base)
Assert.IsTrue(ExtendsResult.IsExtendsTrue(R))
})
// ------------------------------------------------------------------
// Invariant
Expand Down
Loading