Skip to main content

TypeGuard

Enum TypeGuard 

Source
pub enum TypeGuard {
    Typeof(TypeofKind),
    Instanceof(TypeId),
    LiteralEquality(TypeId),
    NullishEquality,
    Truthy,
    Discriminant {
        property_path: Vec<Atom>,
        value_type: TypeId,
    },
    InProperty(Atom),
    Predicate {
        type_id: Option<TypeId>,
        asserts: bool,
    },
    Array,
    ArrayElementPredicate {
        element_type: TypeId,
    },
}
Expand description

AST-agnostic representation of a type narrowing condition.

This enum represents various guards that can narrow a type, without depending on AST nodes like NodeIndex or SyntaxKind.

§Examples

typeof x === "string"     -> TypeGuard::Typeof(TypeofKind::String)
x instanceof MyClass      -> TypeGuard::Instanceof(MyClass_type)
x === null                -> TypeGuard::NullishEquality
x                         -> TypeGuard::Truthy
x.kind === "circle"       -> TypeGuard::Discriminant { property: "kind", value: "circle" }

Variants§

§

Typeof(TypeofKind)

typeof x === "typename"

Narrows a union to only members matching the typeof result. For example, narrowing string | number with Typeof(TypeofKind::String) yields string.

§

Instanceof(TypeId)

x instanceof Class

Narrows to the class type or its subtypes.

§

LiteralEquality(TypeId)

x === literal or x !== literal

Narrows to exactly that literal type (for equality) or excludes it (for inequality).

§

NullishEquality

x == null or x != null (checks both null and undefined)

JavaScript/TypeScript treats == null as matching both null and undefined.

§

Truthy

x (truthiness check in a conditional)

Removes falsy types from a union: null, undefined, false, 0, "", NaN.

§

Discriminant

x.prop === literal or x.payload.type === "value" (Discriminated Union narrowing)

Narrows a union of object types based on a discriminant property.

§Examples

  • Top-level: { kind: "A" } | { kind: "B" } with path: ["kind"] yields { kind: "A" }
  • Nested: { payload: { type: "user" } } | { payload: { type: "product" } } with path: ["payload", "type"] yields { payload: { type: "user" } }

Fields

§property_path: Vec<Atom>

Property path from base to discriminant (e.g., [“payload”, “type”])

§value_type: TypeId

The literal value to match against

§

InProperty(Atom)

prop in x

Narrows to types that have the specified property.

§

Predicate

x is T or asserts x is T (User-Defined Type Guard)

Narrows a type based on a user-defined type predicate function.

§Examples

function isString(x: any): x is string { ... }
function assertDefined(x: any): asserts x is Date { ... }

if (isString(x)) { x; // string }
assertDefined(x); x; // Date
  • type_id: Some(T): The type to narrow to (e.g., string or Date)
  • type_id: None: Truthiness assertion (asserts x), behaves like Truthy
  • asserts: true: This is an assertion (throws if false), affects control flow

Fields

§type_id: Option<TypeId>
§asserts: bool
§

Array

Array.isArray(x)

Narrows a type to only array-like types (arrays, tuples, readonly arrays).

§Examples

function process(x: string[] | number | { length: number }) {
  if (Array.isArray(x)) {
    x; // string[] (not number or the object)
  }
}

This preserves element types - string[] | number[] stays as string[] | number[], it doesn’t collapse to any[].

§

ArrayElementPredicate

array.every(predicate) where predicate has type predicate

Narrows an array’s element type based on a type predicate.

§Examples

const arr: (number | string)[] = ['aaa'];
const isString = (x: unknown): x is string => typeof x === 'string';
if (arr.every(isString)) {
  arr; // string[] (element type narrowed from number | string to string)
}

This only applies to arrays. For non-array types, the type is unchanged.

Fields

§element_type: TypeId

The type to narrow array elements to

Trait Implementations§

Source§

impl Clone for TypeGuard

Source§

fn clone(&self) -> TypeGuard

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for TypeGuard

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl PartialEq for TypeGuard

Source§

fn eq(&self, other: &TypeGuard) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl StructuralPartialEq for TypeGuard

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<S, T> Upcast<T> for S
where T: UpcastFrom<S> + ?Sized, S: ?Sized,

Source§

fn upcast(&self) -> &T
where Self: ErasableGeneric, T: ErasableGeneric<Repr = Self::Repr>,

Perform a zero-cost type-safe upcast to a wider ref type within the Wasm bindgen generics type system. Read more
Source§

fn upcast_into(self) -> T
where Self: Sized + ErasableGeneric, T: ErasableGeneric<Repr = Self::Repr>,

Perform a zero-cost type-safe upcast to a wider type within the Wasm bindgen generics type system. Read more
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more