我想這樣做,但this.element不能分配給我不明白爲什麼打字稿泛型類型HTML元素包裹
class Elem<T> {
public element : T;
constructor(typeElement:string){
this.element = document.createElement(typeElement);
}
}
,你可以看到playground
我想這樣做,但this.element不能分配給我不明白爲什麼打字稿泛型類型HTML元素包裹
class Elem<T> {
public element : T;
constructor(typeElement:string){
this.element = document.createElement(typeElement);
}
}
,你可以看到playground
你舉的例子是非常接近時,唯一的問題是T應該表示它擴展了HTMLElement,然後你必須將HTMLElement轉換爲在構造函數中輸入T(不知道爲什麼)。
// cast T as type HTMLElement
class Elem<T extends HTMLElement> {
public element: T;
constructor(typeElement: string) {
// had to cast HTMLElement to type T....
// odd because T extends HTMLElement, but it works
this.element = <T>document.createElement(typeElement);
}
}
var e = new Elem('div');
e.element.innerHTML = 'generic class test';
document.body.appendChild(e.element);
你可以看到它在playground
我相信這不會一路走來。 'e.element'是一個基本的'HTMLElement',除非你指定'new Elem
工作「我想這樣做」 - 什麼是*是*? – m02ph3u5