gpt4 book ai didi

typescript - 声明一个 HTMLElement typescript

转载 作者:搜寻专家 更新时间:2023-10-30 20:29:31 26 4
gpt4 key购买 nike

在 visual studio 的默认 TypeScript HTML 应用程序中,我添加了

HTMLElement 

到 window.onload 事件处理程序的第一行,认为我可以为“el”提供一个类型。

因此:

class Greeter {
element: HTMLElement;
span: HTMLElement;
timerToken: number;

constructor (element: HTMLElement) {
this.element = element;
this.element.innerText += "The time is: ";
this.span = document.createElement('span');
this.element.appendChild(this.span);
this.span.innerText = new Date().toUTCString();
}

start() {
this.timerToken = setInterval(() => this.span.innerText = new Date().toUTCString(), 500);
}

stop() {
clearTimeout(this.timerToken);
}

}

window.onload = () => {
HTMLElement el = document.getElementById('content');
var greeter = new Greeter(el);
greeter.start();
};

我得到一个错误

Compile Error. See error list for details .../app.ts (25,17): Expected ';'

有什么线索吗?我怀疑我遗漏了一些明显的东西。

最佳答案

类型在 TypeScript 中名称之后,部分原因是类型是可选的。

所以你的台词:

HTMLElement el = document.getElementById('content');

需要更改为:

const el: HTMLElement = document.getElementById('content');

早在 2013 年,HTMLElement 类型就可以从 getElementById 的返回值中推断出来,如果您不使用 strict,情况仍然如此空值检查(但您应该使用 TypeScript 中的严格模式)。如果您执行严格的空值检查,您会发现 getElementById 的返回类型已从 HTMLElement 更改为 HTMLElement |空。更改使类型更正确,因为您并不总能找到元素。

因此,当使用类型模式时,编译器会鼓励您使用类型断言来确保您找到了一个元素。像这样:

const el: HTMLElement | null = document.getElementById('content');

if (el) {
const definitelyAnElement: HTMLElement = el;
}

我已经包含了类型来演示运行代码时会发生什么。有趣的是,elif 语句中具有更窄的类型 HTMLElement,因为您消除了它为 null 的可能性。

您可以使用相同的结果类型做完全相同的事情,而无需任何类型注释。它们将由编译器推断,从而节省所有额外的输入:

const el = document.getElementById('content');

if (el) {
const definitelyAnElement = el;
}

关于typescript - 声明一个 HTMLElement typescript ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14742194/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com