🌐
TypeScript
typescriptlang.org › play › 3-7 › syntax-and-messaging › optional-chaining.ts
TypeScript: Playground Example - Optional Chaining
type AlbumAPIResponse = { title: string; artist?: { name: string; bio?: string; previousAlbums?: string[]; }; }; declare const album: AlbumAPIResponse; // With optional chaining, you can write code like this: const artistBio = album?.artist?.bio; // Instead of: const maybeArtistBio = album.artist ...
🌐
TypeScript
typescriptlang.org › docs › handbook › release-notes › typescript-3-7.html
TypeScript: Documentation - TypeScript 3.7
At its core, optional chaining lets us write code where TypeScript can immediately stop running some expressions if we run into a null or undefined. The star of the show in optional chaining is the new ?. operator for optional property accesses.
🌐
GeeksforGeeks
geeksforgeeks.org › typescript › how-optional-chaining-works-in-typescript
How optional chaining works in TypeScript ? - GeeksforGeeks
March 22, 2022 - TypeScript Optional Chaining is the process of searching and calling variables, methods, parameters that might be nil in existence.
🌐
Marius Schulz
mariusschulz.com › blog › optional-chaining-the-operator-in-typescript
Optional Chaining: The ?. Operator in TypeScript — Marius Schulz
September 11, 2021 - Otherwise, produce the value of options.formatting.indent. Note that the ?. operator always produces the value undefined when it stops descending into a property chain, even when it encounters the value null. TypeScript models this behavior in its type system. In the following example, TypeScript infers the indent local variable to be of type number | undefined:
🌐
Medium
medium.com › inside-rimeto › optional-chaining-in-typescript-622c3121f99b
Optional Chaining in TypeScript. Traversing tree-like structures safely… | by Neville Bowers | Inside Rimeto | Medium
December 4, 2019 - This statement is by far the most ... development-time tooling benefits. What’s the catch? TypeScript unfortunately does not yet support an optional chaining operator....
🌐
egghead.io
egghead.io › lessons › typescript-use-the-optional-chaining-operator-in-typescript
Use the Optional Chaining Operator in TypeScript | egghead.io
We're also going to learn how to ... exist using the ?.() syntax. ... Instructor: [0:00] For this example, I've prepared a function called serializeJSON()....
Published   February 17, 2021
🌐
EDUCBA
educba.com › home › software development › software development tutorials › typescript tutorial › typescript optional chaining
TypeScript Optional Chaining | Guide to TypeScript Optional Chaining
April 20, 2023 - With this, we shall conclude the topic ‘TypeScript Optional chaining’. We have seen what Optional chaining in TypeScript is and how it is implemented. It uses an operator ( ?. ) to check for values if present or not. Syntactically, it replaces lines of code used to check existence of the parameters. We have also seen few examples which are easy to understand and also show what errors user might face during Optional chaining.
Address   Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
🌐
GeeksforGeeks
geeksforgeeks.org › typescript › how-to-use-optional-chaining-with-arrays-and-functions-in-typescript
How to use Optional Chaining with Arrays and Functions in TypeScript ? - GeeksforGeeks
May 6, 2024 - We use the optional chaining (?.) for safe access. const result = object?.property?.[index]?.method?.(); Example: Below is the implementation of the above-discussed approach. ... type Approach3 = { username: string; posts?: { title: string; likes?: number; getAuthor?(): string }[]; }; const user: Approach3 | undefined = { username: 'geekUser', posts: [ { title: 'Introduction to TypeScript', likes: 20, getAuthor: () => 'Geek1' }, { title: 'Advanced JavaScript', likes: 15 }, ], }; const res1 = user?.posts?.[0]?.likes; const res2 = user?.posts?.[1]?.getAuthor?.(); console.log(res1); console.log(res2);
🌐
Reddit
reddit.com › r/typescript › how to enforce the use of optional chaining for any type object in typescript?
r/typescript on Reddit: How to enforce the use of optional chaining for any type object in TypeScript?
June 20, 2024 -

I'm trying to enforce the use of optional chaining for accessing properties of any type object in TypeScript to avoid potential runtime errors. For example, I want the following code to throw a TypeScript error:

    catch(e: any) {
        const code = e.code; // This should throw a TypeScript error
    }

But this code should not throw an error:

    catch(e: any) {
        const code = e?.code; // This should not throw a TypeScript error
    }

Is there a way to configure TypeScript to enforce this rule or any workaround to achieve this behavior?

Find elsewhere
🌐
Medium
medium.com › @ambily_francis › safely-navigate-objects-with-optional-chaining-in-typescript-878f29d85118
Safely Navigate Objects with Optional Chaining in TypeScript | by Ambily Francis | Medium
March 11, 2024 - In this example, `user.address?.city` checks if `user.address` is defined before trying to access its `city` property. If `user.address` is undefined, the expression evaluates to undefined without throwing an error. The optional chaining operator in TypeScript, introduced in version 3.7 and higher, provides a safer way to access nested properties in objects.
🌐
Scaler
scaler.com › home › topics › typescript › optional chaining and nullish coalescing in typescript
Optional Chaining and Nullish Coalescing in TypeScript - Scaler Topics
May 4, 2023 - Produce the value of options.formatting.indent otherwise. When the?. operator finishes descending into a property chain, it always returns the value undefined, even if it meets the value null. TypeScript's type system emulates this behavior. TypeScript infers that the indent local variable in the following example is of type number | undefined :
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Operators › Optional_chaining
Optional chaining (?.) - JavaScript | MDN
This is an idiomatic pattern in JavaScript, but it gets verbose when the chain is long, and it's not safe. For example, if obj.first is a Falsy value that's not null or undefined, such as 0, it would still short-circuit and make nestedProp become 0, which may not be desirable. With the optional chaining operator (?.), however, you don't have to explicitly test and short-circuit based on the state of obj.first before trying to access obj.first.second:
🌐
Valentino G.
valentinog.com › blog › chaining
Using Optional Chaining in TypeScript and JavaScript
February 7, 2020 - Next up generate a configuration file for TypeScript: ... Once done create a new JavaScript file and name it as you wish, I called mine optional_chaining.js.
🌐
InfoWorld
infoworld.com › home › software development › typescript 3.7 arrives with optional chaining
TypeScript 3.7 arrives with optional chaining | InfoWorld
November 6, 2019 - Optional chaining uses a new ?. operator for optional property accesses. Also included are two other operations: optional element access, for accessing non-identifier properties such as numbers and arbitrary strings, and optional call, for conditionally calling expressions if they are not null or undefined.
🌐
LogRocket
blog.logrocket.com › home › optional chaining and nullish coalescing in typescript
Optional chaining and nullish coalescing in TypeScript - LogRocket Blog
June 4, 2024 - For example, in Person::getUppercaseFullName() we return undefined if the full name is not defined. This way of implementing things is quite cumbersome and difficult to both read and maintain.
🌐
TutorialsPoint
tutorialspoint.com › how-optional-chaining-works-in-typescript
How optional chaining works in TypeScript?
In this article, you will understand how optional chaining works in TypeScript. Optional chaining operator (?.) accesses an object’s property. If the objects property is null or not defined, it returns ‘undefined’. Let us first understand what TypeSc
Top answer
1 of 3
20

At time of writing, TypeScript does not support the optional chaining operator. See discussion on the TypeScript issue tracker: https://github.com/Microsoft/TypeScript/issues/16

As a warning, the semantics of this operator are still very much in flux, which is why TypeScript hasn't added it yet. Code written today against the Babel plugin may change behavior in the future without warning, leading to difficult bugs. I generally recommend people to not start using syntax whose behavior hasn't been well-defined yet.

2 of 3
12

Update Oct 15, 2019

Support now exists in [email protected]

Say thanks to https://stackoverflow.com/a/58221278/6502003 for the update!


Although TypeScript and the community are in favor of this operator, until TC39 solidifies the current proposal (which at the time of this writing is at stage 1) we will have to use alternatives.

There is one alternative which gets close to optional chaining without sacrificing dev tooling: https://github.com/rimeto/ts-optchain

This article chronicles what the creators were able to achieve in trying to mirror the native chaining operator:

  1. Use a syntax that closely mirrors chained property access
  2. Offer a concise expression of a default value when traversal fails
  3. Enable IDE code-completion tools and compile-time path validation

In practice it looks like this:

import { oc } from 'ts-optchain';

// Each of the following pairs are equivalent in result.
oc(x).a();
x && x.a;

oc(x).b.d('Default');
x && x.b && x.b.d || 'Default';

oc(x).c[100].u.v(1234);
x && x.c && x.c[100] && x.c[100].u && x.c[100].u.v || 1234;

Keep in mind that alternatives like this one will likely be unnecessary once the proposal is adopted by TypeScript.

Also, a big thanks to Ryan Cavanaugh for all the work you are doing in advocating this operator to TC39!

Top answer
1 of 2
28

The problem is you are targeting esnext this will tell the compiler to output all language features as is without any transpilation. Set the language to es2020 (or below) and ?. and ?? will get transpiled to compatible code:

Copy(async function () {
    let imageFileId = (await db.query(sql`select id from image_files where sha256=${sha256}`))[0]?.id;
})()

Playground Link

There is no fine-grained control over which language features get transpiled and which don't do you have to pick a version as a whole unfortunately,

2 of 2
5

Well, I didn't want to use Babel because then I'd have to figure out how to replace ts-node. There's a bunch of outdated docs out there referring to old Babel packages, but these instructions should work as of Nov 2019:

Add a .babelrc file:

Copy{
    "presets": [
        ["@babel/preset-env",{"targets": {"node": "current"}}],
        "@babel/preset-typescript"
    ],
    "plugins": [
        "@babel/plugin-syntax-bigint"
    ]
}

Add these deps:

Copy  "devDependencies": {
    "@babel/cli": "^7.7.0",
    "@babel/core": "^7.7.0",
    "@babel/node": "^7.7.0",
    "@babel/plugin-syntax-bigint": "^7.4.4",
    "@babel/preset-env": "^7.7.1",
    "@babel/preset-typescript": "^7.7.0",
    "@types/node": "^12.7.5",
    "typescript": "^3.7.2"
  }

Execute your code with:

Copynode_modules/.bin/babel-node --extensions ".ts" src/index.ts

The --extensions ".ts" is very important, even though you're explicitly trying to execute a .ts file, it won't transpile it w/out that.

I like to use GNU Make instead of package.json scripts:

CopyMAKEFLAGS += --no-builtin-rules
.SUFFIXES:
NM := node_modules/.bin
.PHONY: build start dev clean test publish

## commands
########################################

__default:
    $(error Please specify a target)

build: build-types build-js dist/package.json

build-types: node_modules/.yarn-integrity
    $(NM)/tsc --emitDeclarationOnly

build-js: node_modules/.yarn-integrity
    $(NM)/babel src --out-dir dist --extensions ".ts" --source-maps inline

run: node_modules/.yarn-integrity
    $(NM)/babel-node --extensions ".ts" src/index.ts

check: node_modules/.yarn-integrity
    $(NM)/tsc --noEmit

dist:
    mkdir -p $@

clean:
    rm -rf node_modules dist yarn-error.log

dist/package.json: package.json | dist
    jq 'del(.private, .devDependencies, .scripts, .eslintConfig, .babel)' $< > $@

## files
########################################

node_modules/.yarn-integrity: yarn.lock
    @yarn install --frozen-lockfile --production=false --check-files
    @touch -mr $@ $<

yarn.lock: package.json
    @yarn check --integrity
    @touch -mr $@ $<

Or just copy from Microsoft's TypeScript Babel Starter.

🌐
TypeScript ESlint
typescript-eslint.io › rules › prefer-optional-chain
prefer-optional-chain | typescript-eslint
When this option is true, the rule will provide an auto-fixer for cases where the return type of the expression would change. For example for the expression !foo || foo.bar the return type of the expression is true | T, however for the equivalent optional chain foo?.bar the return type of the ...
🌐
JavaScript.info
javascript.info › tutorial › the javascript language › objects: the basics
Optional chaining '?.'
The optional chaining ?. is not an operator, but a special syntax construct, that also works with functions and square brackets. For example, ?.() is used to call a function that may not exist.