typescript 声明一个 HTMLElement 打字稿
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14742194/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Declaring an HTMLElement Typescript
提问by bnieland
In the default TypeScript HTML app from visual studio, I added
在 Visual Studio 的默认 TypeScript HTML 应用程序中,我添加了
HTMLElement
to the first line of the window.onload event handler, thinking that I could provide a type for "el".
到 window.onload 事件处理程序的第一行,认为我可以为“el”提供一个类型。
thus:
因此:
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();
};
I get an error
我收到一个错误
Compile Error. See error list for details .../app.ts (25,17): Expected ';'
编译错误。有关详细信息,请参阅错误列表 .../app.ts (25,17): 预期的 ';'
Any clue why? I suspect I am missing something obvious.
任何线索为什么?我怀疑我遗漏了一些明显的东西。
回答by Fenton
The type comes afterthe name in TypeScript, partly because types are optional.
类型在 TypeScript 中出现在名称之后,部分原因是类型是可选的。
So your line:
所以你的线路:
HTMLElement el = document.getElementById('content');
Needs to change to:
需要更改为:
const el: HTMLElement = document.getElementById('content');
Back in 2013, the type HTMLElement
would have been inferred from the return value of getElementById
, this is still the case if you aren't using strict null checks(but you oughtto be using the strict modes in TypeScript). If you are enforcing strict null checks you will find the return type of getElementById
has changed from HTMLElement
to HTMLElement | null
. The change makes the type more correct, because you don't always find an element.
早在 2013 年,类型HTMLElement
就会从 的返回值推断出来getElementById
,如果您不使用严格的空检查(但您应该使用 TypeScript 中的严格模式),情况仍然如此。如果您强制执行严格的空检查,您会发现 的返回类型getElementById
已从 更改HTMLElement
为HTMLElement | null
。更改使类型更正确,因为您并不总是能找到元素。
So when using type mode, you will be encouraged by the compiler to use a type assertion to ensure you found an element. Like this:
因此,在使用类型模式时,编译器会鼓励您使用类型断言来确保找到元素。像这样:
const el: HTMLElement | null = document.getElementById('content');
if (el) {
const definitelyAnElement: HTMLElement = el;
}
I have included the types to demonstrate what happens when you run the code. The interesting bit is that el
has the narrower type HTMLElement
within the if
statement, due to you eliminating the possibility of it being null.
我已经包含了类型来演示运行代码时会发生什么。有趣的一点是,el
拥有更小的类型HTMLElement
的内if
声明,由于你消除它是空的可能性。
You can do exactly the same thing, with the same resulting types, without any type annotations. They will be inferred by the compiler, thus saving all that extra typing:
您可以使用相同的结果类型做完全相同的事情,而无需任何类型注释。它们将由编译器推断,从而节省所有额外的输入:
const el = document.getElementById('content');
if (el) {
const definitelyAnElement = el;
}
回答by bnieland
Okay: weird syntax!
好的:奇怪的语法!
var el: HTMLElement = document.getElementById('content');
fixes the problem. I wonder why the example didn't do this in the first place?
解决问题。我想知道为什么这个例子一开始没有这样做?
complete code:
完整代码:
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 = () => {
var el: HTMLElement = document.getElementById('content');
var greeter = new Greeter(el);
greeter.start();
};
回答by Vincent Ottens
In JavaScript you declare variables or functions by using the keywords var, let or function. In TypeScript classes you declare class members or methods without these keywords followed by a colon and the type or interface of that class member.
在 JavaScript 中,您可以使用关键字 var、let 或 function 来声明变量或函数。在 TypeScript 类中,您声明类成员或方法时不带这些关键字,后跟冒号和该类成员的类型或接口。
It's just syntax sugar, there is no difference between:
这只是语法糖,两者之间没有区别:
var el: HTMLElement = document.getElementById('content');
and:
和:
var el = document.getElementById('content');
On the other hand, because you specify the type you get all the information of your HTMLElement object.
另一方面,因为您指定了类型,所以您将获得 HTMLElement 对象的所有信息。
回答by Dale Hurtt
Note that const declarations are block-scoped.
请注意,const 声明是块范围的。
const el: HTMLElement | null = document.getElementById('content');
if (el) {
const definitelyAnElement: HTMLElement = el;
}
So the value of definitelyAnElement is not accessible outside of the {}.
因此,在 {} 之外无法访问 absoluteAnElement 的值。
(I would have commented above, but I do not have enough Reputation apparently.)
(我会在上面发表评论,但显然我没有足够的声誉。)