- Error
- Reported by the lexer and parser
TS1162
An object member cannot be declared optional.
A method or property in an object literal is marked optional with `?`. Optional markers belong in types, not in object literals.
What it means
In an object literal every member exists, so ? after a member name has no meaning. Optional members are declared in the object's type (an interface or type literal).
Example
export const o = { a?() { return 1; } };
ts-r-check -p tsconfig.json --pretty false ts-r outputindex.ts(1,21): error TS1162: An object member cannot be declared optional.
Recorded by node scripts/verify-examples.mjs with ts-r built from commit 6deaf01. The example uses the default tsconfig: strict, target: es2022, module: esnext, moduleResolution: bundler.
How to fix
- Remove the
?. - Declare the optional member in a type and annotate the object with it:
const o: { a?(): number } = {}.