-
Notifications
You must be signed in to change notification settings - Fork 13k
Closed
Labels
DuplicateAn existing issue was already createdAn existing issue was already created
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.
Metadata
Metadata
Assignees
Labels
DuplicateAn existing issue was already createdAn existing issue was already created