4 ms·
For me (coming from C++) being able to easily union and intersect types, and being able to specify certain values (not sure the right name for this). For exampl
by xsmasher 4y ago
For me (coming from C++) being able to easily union and intersect types, and being able to specify certain values (not sure the right name for this). For example:
type ServerResponse = {success:true, response:JSON} | {success:false, error:string};
In C++ I would probably have to type success:boolean, and make response and error optionals, but the TS type is more expressive.
if success==true, then response must exist.
if success==false, then error must exist.
const sr: ServerResponse = {success:true, error:"moo"); // won't compile, doesn't match
TS understands this type really well, and type narrowing makes it easy to work with.
// NOT LEGAL; error might not exist
console.log(sr.error);
// IS LEGAL; we test for success first, which narrows the type.
if(sr.success){
console.log(sr.response);
} else {
console.log(sr.error);
}
- xsmasher 4y agoToo late to EDIT: but "literal types" was the word I am looking for. I used "success:true" and "success:false" as part of the two types I was combining; it seems like "success:boolean" would server the same function, but it does not. The type I created has more information that that. https://www.typescriptlang.org/docs/handbook/literal-types.html https://www.typescriptlang.org/docs/handbook/literal-types.h...
- patates 4y agoI'm a big fan of TS, but discriminated unions are available in a lot of languages and when not, there's usually some library adding it like boost::variant if the language has runtime types or templating/macros.
- comex 4y agoC++ has std::variant these days, no need for Boost… however, neither version has particularly good ergonomics.
- wiseowise 4y ago> boost No, thanks.
- xsmasher 4y agoIf I understand std::variant, it THROWS if you try to access the wrong type? I should have been specific, but all of the errors I mention above are compile-time errors, not run-time.