Re:TypeScript’s quirks: How inconsistencies make the languag...
by IggleSniggle on Saturday February 01, 2020 @02:34PM
(#22212679)
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/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.
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.
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/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.