Skip to content

Suggestion: Automatic type guard generation #15265

Closed

Description

Imagine we want to deserialize some JSON object and then extract some information from it, this is a very common task. We expect the JSON data to be of a certain type, so wouldnt it be good if we could declare some type for our JSON:

interface Example {
    name: string;
    age: number;
    contactDetails: {
        address: string;
        phone: string
    }
}

and have an automatically generated type guard isExample(o : any): o is Example
like this:

function isExample(o) {
    return 'name' in o && typeof o.name === 'string' &&
               'age' in o && typeof o.age === 'number' &&
               'contactDetails' in o && typeof o.contactDetails === 'object' &&
                   'address' in o.contactDetails && typeof o.contactDetails.address === 'string' &&
                   'address' in o.phone && typeof o.contactDetails.phone === 'string';
}

So now I can do

let json = getJson()
if(isExample(json)){
   // use it as an Example, it definitely implements Example
} else {
  // throw some error
}
  • caveat: I realize you cannot validate a function type at runtime like (s: string) => number, so just ignore those cases, and throw a compile error if someone tries to generate an automatic guard for a type that has a function type nested in it somewhere.
  • caveat: You should only generate the type guard if it used, so there shouldn't be type guards generated for any type I define.

The syntax I would like for this is is<T>(o: any): o is T so i can use it like is<Example>(json)
what's good about it is that is is already a keyword.
And this would generate a type guard in javascript like is_Example(o){...} or something.

Activity

  1. gcnew commented on Apr 19, 2017

    @gcnew
    Contributor
  2. RyanCavanaugh commented on Apr 19, 2017

    @RyanCavanaugh
    Member

    Previously discussed at #3628 / #1573. Remains out of scope.

  3. locked and limited conversation to collaborators on Jun 14, 2018
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

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions