When trying to add a gradient to a line chart, I needed to get it's canvas. Before proceeding with the canvas I added a typecheck, however Vetur remarked that the "Object is possibly 'null'.Vetur(2531)"
mounted() {
const canv = document.getElementById("line-chart") as HTMLCanvasElement;
if (canv !== null && canv !== undefined) {
const gradient = canv
.getContext("2d")
.createLinearGradient(0, 0, 0, canv.height);
After researching I attempted to use the optional chaining operator to type check. This approach works, as no error is reported.
mounted() {
const canv = document.getElementById("line-chart") as HTMLCanvasElement;
const gradient = canv
?.getContext("2d")
?.createLinearGradient(0, 0, 0, canv.height);
I'm confused as to why the first approach doesn't work, since canv is a const, thus can't change. A type check should be enough.
Why is only the optional chaining working in this case?