|
|
|
|
|
by xsmasher
1200 days 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);
}
|
|
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.h...