3 ms·
The two things miss in TypeScript coming from C#: Pattern matching: if (thing is Person person) { var name = person.Name } Safe navigatio
by miguelrochefort 8y ago
The two things miss in TypeScript coming from C#:
Pattern matching:
if (thing is Person person)
{
var name = person.Name
}
Safe navigation operator:
var countryName = person.Address?.Country ?? "Unknown";
Type guards are a pain to deal with.
- patates 8y agoLack of the safe navigation operator is a real PITA. You can replace "??" with "||" (more or less), but no solution exists for "?." and I don't know how I lived without it before.
- vimslayer 8y agoLuckily, we'll probably get it sooner or later [1]. There are also a bunch of typesafe getter function utility libraries that are better than nothing [2-3]. [1] https://github.com/tc39/proposal-optional-chaining https://github.com/tc39/proposal-optional-chaining [2] https://github.com/pimterry/typesafe-get https://github.com/pimterry/typesafe-get [3] https://github.com/yayoc/optional-chain https://github.com/yayoc/optional-chain
- seanwilson 8y agoMaybe I'm missing something but can't you do this for the second one where countryName will be undefined if it's not set? var person = {address:{country:"uk"}} var {address: {country: countryName}} = person
- vimslayer 8y agoThat would work, but what if the `Person` type's address can also be null? The following would be an error either at runtime or - in the case of TypeScript - at compile time. var person = {address: null} var {address: {country: countryName}} = person
- seanwilson 8y agoHmm, that's annoying behaviour. This doesn't give a runtime error: var [a,b,c] = [1] Either way, I'd highly recommend just using TypeScript.
- vimslayer 8y agoRight, because while b and c will be undefined, they are taken from an existing array, not from null/undefined. This will throw var [a, b, c] = null and this (destructing a nested array) var [[a]] = [] the point of the "elvis" ?. operator is to make accessing properties _of_ optional values or other optional properties easier. "Either way, I'd highly recommend just using TypeScript." Sure, I'd recommend that too, but in this case it "only" helps us by moving the error from runtime to compile-time, nested optional property access remains ugly in the TS world, too. The ?. operator will come to TypeScript as soon as it comes to EcmaScript.
- kylestlb 8y agoRe safe navigation operator... the idea is to basically port lodash's _.get into an operator, right?
- vimslayer 8y agoBasically, but with type safety and a decent runtime performance