Let’s say we have a variable that is optional string text
. Is there a way to optionally unwrap this property? In Swift, we can do something like:
guard let unwrappedText = text else { return }
In our code, we have a lot of these:
if (!text) return
Which is fine, but later on, the type of text
is still an optional string so we still have to deal with unwrapping. Ideally we can check for null and unwrap the variable at the same time. I might not have the right term for this because I can’t seem to find anything online about conditional unwraps for TypeScript.
The TypeScript compiler is smart enough to know when an optional type like string | undefined
has been narrowed to an exact type. For example:
function foo(data?: string) { // Here the type of data is string | undefined
if (!data) return;
data; // Here the type of data is string
}
You can see this in action on the TypeScript playground: https://www.typescriptlang.org/play?ssl=5&ssc=2&pln=1&pc=1#code/GYVwdgxgLglg9mABMOcAUATAhlLB+ALkQGcoAnGMAcwEpEBvAKERcRmETQEJtc6yAplBBkwAbkbNWvLBIC+koA
There are also more explicit options for type narrowing in Typescript.
How exactly would you use this? Possibly you just want optional chaining
maybeString?.toUpperCase()
. Maybe null coalescing,??
.yeah exactly. instead of always having to unwrap it in future uses (since the
if (!text) return
already handles the case of it being null. coming from swift where optionals are natively built into the language, doing a null check and then a force unwrap seems slightly weirdIt actually does work exactly like you think it should. See typescriptlang.org/play?#code/…. Do you have a minimal example that shows otherwise?