Javascript 带有HTML5画布的TypeScript 3.9--.strokeStyle上出现错误

Javascript 带有HTML5画布的TypeScript 3.9--.strokeStyle上出现错误,javascript,typescript,html5-canvas,typescript-typings,Javascript,Typescript,Html5 Canvas,Typescript Typings,不确定如何解决该问题,但我面临一个错误,该错误不允许对线条的笔划进行着色: 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)

不确定如何解决该问题,但我面临一个错误,该错误不允许对线条的笔划进行着色:

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()
那个?。在JavaScript中,因此在TypeScript中 允许读取位于连接对象链深处的属性的值,而无需明确验证链中的每个引用是否有效。它不允许你这样做。此功能已被禁用

目前,如果要将属性分配给可能为null或未定义的对象,则必须自己编写代码,而不使用?:

事实上,考虑到你一直在使用?。在同一个对象上,我认为如果只检查该对象是否为空,然后使用常规属性访问,您会更高兴:

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();
好吧,希望这会有帮助;祝你好运


很高兴知道可选链接不允许指定属性。我们将在将来牢记这一点。非常感谢。
if (c !== null) c.strokeStyle = "red"; // okay
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();