saw number of issues tried suggestions, so far no luck. Currently
using vsc version 1.76.2, Node 16.14.2 ts version 4.6.4 from ng version command
barChartData is
public barChartData: ChartData<'bar'> = {
labels: [],
datasets: [
{
data: [],
// data: [65, 59, 80, 81, 56, 55, 40],
// backgroundColor: ['#012169', '#0073cf', '#646464', '#012169', '#0073cf', '#646464', '#012169'],
// hoverBackgroundColor: ['#8090b4', '#80b9e7', '#919191', '#8090b4', '#80b9e7', '#919191', '#8090b4'],
},
]
};
it is part of Chart.js v 3.9.1 the labels can be undefined
in vsc a popup shows
(property) ChartData<"bar", number[], unknown>.labels?: unknown[] | undefined
the event handler is where the error is happening:
public chartClicked(e: any): void {
this.barChartData.labels?[0];
console.log(e);
}
I get an error of
':' expected.ts(1005)
and when trying to build from ng serve
./src/app/components/test03/test03.component.ts:127:69 - Error: Module parse failed: Unexpected token (127:69)
File was processed with these loaders:
* ./node_modules/@angular-devkit/build-angular/src/babel/webpack-loader.js
* ./node_modules/@ngtools/webpack/src/ivy/index.js
You may need an additional loader to handle the result of these loaders.
| }
| chartClicked(e) {
> console.log(this.barChartData.labels ? [e.active[0].index] : );
| console.log(e);
| }
Error: src/app/components/test03/test03.component.ts:135:61 - error TS1005: ':' expected.
135 console.log(this.barChartData.labels?[e.active[0].index]);
~
× Failed to compile.
how to resolve this?
3
Answers
?.
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.The
?
question mark is in your code as seen in the error:and because you only put
?
and not?.
, it interprets that as the ternary operator and not the optional chaining operator.To use the optional chaining operator with brackets, you still have to add a dot after the question mark:
MDN Reference
You need a
.
to use optional chaining with arrays. Changethis.barChartData.labels?[0];
tothis.barChartData.labels?.[0];