You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Suggestion: Automatic type guard generation #15265
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:
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
gcnew commentedon Apr 19, 2017
You might be interested in https://github.com/gcanti/io-ts or https://github.com/pelotom/runtypes.
RyanCavanaugh commentedon Apr 19, 2017
Previously discussed at #3628 / #1573. Remains out of scope.