Videos
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?
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.
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:
- Use a syntax that closely mirrors chained property access
- Offer a concise expression of a default value when traversal fails
- 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!
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,
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.