🌐
TypeScript
typescriptlang.org › play › 3-7 › syntax-and-messaging › optional-chaining.ts
TypeScript: Playground Example - Optional Chaining
This can replace code where you would traditionally write something like: if (func) func() For example here's an optional call to the callback from an API request: const callUpdateMetadata = (metadata: any) => Promise.resolve(metadata); // Fake API call const updateAlbumMetadata = async (metadata: ...
🌐
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:
🌐
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:
🌐
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
🌐
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 :
🌐
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.
🌐
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....
🌐
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.
🌐
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?

🌐
GitHub
github.com › rimeto › ts-optchain
GitHub - rimeto/ts-optchain: Optional Chaining for TypeScript
While TypeScript is helpful in requiring the necessary existence checks at compile-time, the final code is still quite cumbersome. For example, given the interfaces: interface IAddress { street?: string; city?: string; state?: string; postalCode?: string; } interface IHome { address?: IAddress; phoneNumber?: string; } interface IUser { home?: IHome; } Without support for optional chaining built into TypeScript yet, an implementation for a method to extract the home street string from this structure would look like:
Starred by 578 users
Forked by 16 users
Languages   TypeScript 98.0% | JavaScript 2.0%
Find elsewhere
🌐
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.
🌐
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.
🌐
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);
🌐
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.
🌐
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
🌐
InfoWorld
infoworld.com › home › software development › programming languages › javascript
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.
🌐
Dmitri Pavlutin
dmitripavlutin.com › javascript-optional-chaining
How to Use JavaScript Optional Chaining
In the case of movieSmall, the property director is missing. As a result, movie.director?.name evaluates to undefined. The optional chaining operator prevents throwing TypeError: Cannot read property 'name' of undefined.
🌐
Stack Overflow
stackoverflow.com › questions › 75322578 › how-do-you-get-data-showing-with-typescript-optional-chaining
How do you get data showing with TypeScript Optional Chaining - Stack Overflow
It is also important to note that ? optional chaining operator is used in interface where property types have been declared and in functions where we get property value, for example const yardSize = house.yard?.sqft; .
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.

🌐
Medium
sanjanahumanintech.medium.com › what-is-optional-chaining-in-typescript-7d6430e79917
What is Optional Chaining in TypeScript? | by Sanjana Human In Tech | Medium
October 30, 2023 - Type Inference: TypeScript infers the types correctly, accounting for the possibility of undefined at each level. The optional chaining operator ?. can be used in three ways: ... The primary objective of optional chaining is to avoid runtime errors when trying to access properties or methods of an object that might be null or undefined · Termination Behavior: If the base object (a in the above examples) is null or undefined, the full expression immediately evaluates to undefined, without trying to access any further properties or methods.