本文深入解析TypeScript中HTMLElement与Element的区别。Element是通用基类,涵盖所有文档元素;HTMLElement专指HTML元素,提供如style等特有属性。通过对比document.getElementById与querySelector的返回类型,以及TS与MDN规范的差异,帮助开发者准确选择类型,避免类型错误。
TypeScript定义解析
关联代码仓库
github.com/Dartgm/dart…
- TypeScript是微软推出的开源编程工具
- TypeScript作为JavaScript的超集,兼容ES5/ES6标准并扩展其语法
- TypeScript具备Java、C#等后端语言特性,适用于大型企业级开发
- 众多主流项目采用TS,包括VSCode、Angular6、Vue3及React16
- TS类型系统提供编码时的语法提示支持
- 编译阶段通过类型检查可有效预防线上运行错误
TypeScript安装与编译流程
安装步骤
cnpm i typescript -g
编译操作
tsc helloworld.ts
实践操作指南
首先新建文件夹,利用命令行工具进入该目录并运行 code . 命令

随后使用Vscode编辑ts格式文件,并通过输入tsc --init生成tsconfig配置文件,示例如下
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig to read more about this file */
/* Language and Environment */
"target": "es2016",
/* Modules */
"module": "commonjs",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
/* Type Checking */
"strict": true, /* Enable all strict type-checking options. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
}
}
| 名称 | 描述 |
|---|---|
| target | 将es编译成特定的es版本 |
| module | 指定模块默认的生成规范,默认的就是commonjs |
// Basic DataStruct introduction
let married:boolean = true;
let age:number = 10;
let first_name:string = 'guoming';
let arr1:number[] = [1,2,3];
let arr2:Array<number> = [4,5,6]
// tuple, number and type are know to us
let guoming:[string,number] = ['guoming',10];
// enum type
enum Gender {
GIRL,
BOY
}
// basic enum
console.log(Gender.BOY)
console.log(Gender.GIRL)
// const enum
const enum Colors{
RED,YELLOW,BLUE
}
let myColor = [Colors.RED,Colors.YELLOW,Colors.BLUE]
// any type,if there is an variable declared to be any,these variable is the same like the variable in JavaScript
let root:any = document.getElementById('root')
root.style.color = 'red'
let element: (HTMLElement|null) = document.getElementById('root');
element.style.color = 'green';
// null undefined
let x:number;
x=1;
x=undefined;
x=null;
let y:(number|null|undefined)
y=1;
y=null;
y=undefined;TS中HTMLElement与Element的差异分析
注意ts中document.getElementById()返回HTMLElement类型,而document.querySelect()返回Element类型。
二者具体差异何在?
Element为高通用性基类,Document对象下所有元素均继承自它,该接口涵盖各类元素共有的方法与属性。部分接口继承自Element并扩展特定功能以描述具体行为。
例如,HTMLElement接口构成所有HTML元素的基础,SVGElement接口则是所有SVG元素的基础。多数功能在层级更深的接口中进一步定义。
深入探讨
查阅资料发现,关于getElementId和querySelecter在MDN文档与ts规范中存在差异。
- ts规范定义
let res =document.getElementById('test'); //HTMLElement
let el = document.querySelector('# test'); // Element
- mdn文档定义
querySelector与getElementId均返回Element类型。
以上为typescript基本数据类型HTMLElement与Element区别详解,更多TS类型HTMLElement Element相关信息请关注本站其他文章!