Skip to content

Proposal: validate type of object properties #141

@lo1tuma

Description

@lo1tuma

I would like to propose a new function is.propertyOf(object: unknown: key: string, predicate: Predicate): boolean that accepts 3 values and checks:

  1. wether the given object value is an object and
  2. if the given object has an own property with the name key and
  3. that the value of the specified property matches the given predicate

Example Usage:

is.propertyOf(foo, 'bar', is.string);

Why

Given the following example

interface Foo {
  bar?: string;
  baz: number
}

function doStuff(foo?: Foo) {
  if (is.string(foo?.bar)) { // using optional chaining because `foo` might be undefined
    console.log(foo.baz); // typescript still things `foo` could be undefined
  }
}

Unfortunately typescript is not smart enough to understand that within the if block foo is always defined.

Let’s say is.propertyOf is implemented similar to this:

function propertyOf<O extends unknown, K extends keyof Exclude<O, undefined>, P>(obj: O, key: K, predicate: Predicate<P>): obj is Exclude<O, undefined> & Record<K, P> {
  return true;
} 

then the code from above could look like this:

interface Foo {
  bar?: string;
  baz: number
}

function doStuff(foo?: Foo) {
  if (is.propertyOf(foo, 'bar', t.string)) {
    console.log(foo.bar); // typescript now knows two things: foo is an object and its property bar is a string
  }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions