Skip to content

Suggestion: Automatic type guard generation #15265

@matantsu

Description

@matantsu

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.

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