简体   繁体   English

TypeScript 3.9 与 HTML5 Canvas — 错误 on.strokeStyle

[英]TypeScript 3.9 with HTML5 Canvas — error on .strokeStyle

Not sure how to resolve the issue, but I am facing an error that won't let color the strokes of the line:不知道如何解决这个问题,但我遇到了一个错误,它不会让线条的笔触着色:

const canvas = document.querySelector('canvas')! as HTMLCanvasElement;

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

const c = canvas.getContext('2d');

c?.fillRect(100, 100, 100, 100)

c?.beginPath();
c?.moveTo(50, 300)
c?.lineTo(300, 100)
c?.lineTo(400, 300)
c?.strokeStyle = "red" //<=== error occuring
c?.stroke()

The error is: TS2779: The left-hand side of an assignment expression may not be an optional property access.错误是: TS2779: The left-hand side of an assignment expression may not be an optional property access.

Looking deeply in the library, I see that its interface, CanvasFillStrokeStyles is correctly identifying fillStyle :深入查看库,我看到它的界面CanvasFillStrokeStyles正确识别了fillStyle

interface CanvasFillStrokeStyles {
    fillStyle: string | CanvasGradient | CanvasPattern;
    strokeStyle: string | CanvasGradient | CanvasPattern;
    createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasGradient;
    createPattern(image: CanvasImageSource, repetition: string | null): CanvasPattern | null;
    createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, r1: number): CanvasGradient;
}

The optional chaining operator ?. 可选的链接运算符?. in JavaScript (and therefore in TypeScript) permits reading the value of a property located deep within a chain of connected objects without having to expressly validate that each reference in the chain is valid.在 JavaScript 中(因此在 TypeScript 中)允许读取位于连接对象链深处的属性值,而无需明确验证链中的每个引用是否有效。 It does not allow you to assign properties .不允许分配属性 This functionality was considered but deferred to a possible future proposal .这个功能被考虑过,但被推迟到可能的未来提案中。

For now, if you want to assign a property to something that might turn out to be null or undefined , you will have to write that code yourself without using ?.现在,如果您想将属性分配给可能会变成nullundefined的东西,您将不得不自己编写该代码而不使用?. :

if (c !== null) c.strokeStyle = "red"; // okay

In fact, given that you keep using ?.事实上,鉴于您继续使用?. on the same object makes me think you'd be happier just checking that object for nullishness once and then using regular property access after that:在同一个 object 上让我觉得你会更高兴检查object是否无效,然后使用常规属性访问:

if (!c) throw new Error("Where's my 2d context?!");
c.fillRect(100, 100, 100, 100)
c.beginPath();
c.moveTo(50, 300)
c.lineTo(300, 100)
c.lineTo(400, 300)
c.strokeStyle = "red"
c.stroke();

Okay, hope that helps;好的,希望有帮助; good luck!祝你好运!

Playground link to code Playground 代码链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM