[Chartjs]-':' expected.ts(1005) how to fix

3๐Ÿ‘

โœ…

?. is what you probably meant to use (called optional chaining [MDN]). You are missing the .

The reason for the error is because ? in js (and thus typescript) is a conditional (ternary) operator [MDN]. It expects : because that is the syntax of the ternary operator.

let checkMe = true;
console.log(checkMe ? "truthyCase" : "falsyCase");
// outputs "truthyCase"

The ? question mark is in your code as seen in the error:

Error: src/app/components/test03/test03.component.ts:135:61 - error TS1005: ':' expected.
                                            v
135     console.log(this.barChartData.labels?[e.active[0].index]);
                                            ^                   ~

and because you only put ? and not ?., it interprets that as the ternary operator and not the optional chaining operator.

6๐Ÿ‘

To use the optional chaining operator with brackets, you still have to add a dot after the question mark:

this.barChartData.labels?.[0];

MDN Reference

2๐Ÿ‘

You need a . to use optional chaining with arrays. Change this.barChartData.labels?[0]; to this.barChartData.labels?.[0];

Leave a comment