3 ms·
True, discriminated unions don't flow from any, but they can be useful for composing types from any. I suppose I'm saying that the validation function itself i
by IggleSniggle 7y ago
True, discriminated unions don't flow from any, but they can be useful for composing types from any.
I suppose I'm saying that the validation function itself is the precursor to discriminated unions being useful. <any> run through a type predicate function or an assertion type function (https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#assertion-functions https://www.typescriptlang.org/docs/handbook/release-notes/t...) produces a typed object that conforms to your requirements for the type.
I definitely do wish there were some way to create these assertions/validators from the types automatically, but I think that might be impossible.
Apologies for any formatting issues, on mobile:
```
foo:any;
isAnimal(foo);
if(isDog(foo)){
// Dog
} else {
// Cat
}
}
function isAnimal(thing: any): asserts thing is Animal {
if (thing.kind !== "dog" && thing.kind !== "cat && etc){
throw new AssertionError("Not an animal!");
}
```
// ...etc, except that string literals probably exist in an Array or similar, ie types that can be progressively derived / enhanced from the runtime code.