BT

InfoQ Homepage News TypeScript 3.7 Adds Optional Chaining and Coalescing

TypeScript 3.7 Adds Optional Chaining and Coalescing

Bookmarks

The TypeScript team announced the release of TypeScript 3.7, including optional chaining, nullish coalescing, assertion functions, and numerous other developer ergonomic improvements.

Optional chaining is a highly requested feature. As explained by TypeScript program manager Daniel Rosenwasser:

Optional chaining is issue #16 on our issue tracker. For context, there have been over 23,000 issues filed on the TypeScript issue tracker to date. This one was filed over five years ago – before there was even a formal proposal within TC39. For years, we’ve been asked to implement the feature, but our stance has long been not to conflict with potential ECMAScript proposals. Instead, our team recently took the steps to help drive the proposal to standardization, and ultimately to all JavaScript and TypeScript users. In fact, we became involved to the point where we were championing the proposal! With its advancement to stage 3, we’re comfortable and proud to release it as part of TypeScript 3.7.

Optional chaining allows developers to author code where some expressions can immediately stop running with a null or undefined condition through the new ?. operator for optional property access. For example, before optional chaining JavaScript or TypeScript code would look like this:
 

let x = (foo === null || foo === undefined) ? undefined : foo.bar();

if (foo && foo.bar && foo.bar.baz) { // ... }

With optional chaining, this gets replaced by:

let x = foo?.bar();

if (foo?.bar?.baz) { // ... }

The new ?. operator is slightly different than the && operation checks as the optional chaining operator treats valid data such as 0 or empty strings as truthy.

The same operator can also be used on arrays for optional element access if the array exists, and on function calls to call them if the function is not null or undefined.

return arr?.[0]; log?.(`Request started at ${new Date().toISOString()}`);

The TypeScript team also championed the new ECMAScript nullish coalescing operator, ?? . This new operator provides a falling back to a default value when dealing with null or undefined. The ?? operator replaces the use of || when providing an optional default value.

let x = foo ?? bar();

The TypeScript 3.7 release also introduces assertion functions that throw an error when something unexpected happens. Assertions in JavaScript often get used to guard against passing improper types. Before TypeScript 3.7, these checks could not get properly encoded, requiring either less strict checking or type assertions.

A TypeScript goal is to type existing JavaScript constructs in the least disruptive manner. One of TypeScript's assertion function approaches is to ensure that the condition getting checked must be true throughout the containing scope. The other assertion signature does not check for a condition, instead of telling TypeScript that a specific variable or property has a different type.

This release is the most ambitious TypeScript release since the 3.0 release, with many additional features and improvements:

  • Better support for never-Returning Functions
  • Make --declaration and --allowJs work together
  • More recursive type aliases to better support JSON and tuples
  • useDefineForClassFields flag and declare property modifier to better align with the public class fields ECMAScript proposal
  • Build-free editing with project references
  • Uncalled function checks
  • Flatter error reporting
  • // @ts-nocheck in TypeScript files
  • Semicolon formatter option
  • Numerous website and TypeScript Playground improvements

TypeScript 3.7 also introduces a few potentially breaking changes to consider when upgrading to the latest version of TypeScript, mostly as a result of the new features:

  • Changes in DOM type definitions to improve accuracy around nullness
  • Class field mitigations
  • Function truthy checks
  • Local and imported type declarations now conflict
  • API changes to enable the recursive type alias patterns, removal of the typeArguments property

The TypeScript community response has been overwhelmingly positive to this release, and most users report reasonably easy upgrades. For example, Matthew McEachen of PhotoStructure explains via Twitter:

Just updated @PhotoStructure (64k lines of TS) from v3.6.4 to v3.7.2, and only needed to tweak a couple types. Namely coercion from Promise<Maybe<Maybe<T>> to <Maybe<T> | PromiseMaybe<T>> used to work in 3.6, and needs some coaxing in 3.7. Thanks again for TS!`

For more information, read the official TypeScript 3.7 announcement.

The TypeScript team is already working on features for TypeScript 3.8, including new export * as ns syntax, top-level await, private fields, and more.

The TypeScript community recently concluded the second TSConf event on October 11th with TypeScript founder Anders Hejlsberg delivering the keynote on the TypeScript 3.7 release.

TypeScript is open source software available under the Apache 2 license. Contributions and feedback are encouraged via the TypeScript GitHub project and should follow the TypeScript contribution guidelines and Microsoft open source code of conduct.

Rate this Article

Adoption
Style

Hello stranger!

You need to Register an InfoQ account or or login to post comments. But there's so much more behind being registered.

Get the most out of the InfoQ experience.

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Community comments

  • Groovy Baby

    by Søren Glasius /

    Your message is awaiting moderation. Thank you for participating in the discussion.

    I think that the safe reference syntax is pretty Groovy ;-)

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

BT

Is your profile up-to-date? Please take a moment to review and update.

Note: If updating/changing your email, a validation request will be sent

Company name:
Company role:
Company size:
Country/Zone:
State/Province/Region:
You will be sent an email to validate the new email address. This pop-up will close itself in a few moments.