TypeScript是什么?
涉及代碼倉庫
- TypeScript是由微軟開發的一款開源的編程工具
- TypeScript是JavaScript的超集,遵循最新的ES5/ES6規范,TypeScript擴展了JavaScript的語法
- 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;
typescript中HTMLElement 和 Element的區別
你可能會注意到在ts中,通過document.getElementById()返回HTMLElement類型,而document.querySelect()返回Element類型。
那么兩者區別是什么呢?
Element 是一個通用性非常強的基類,所有 Document 對象下的對象都繼承自它。這個接口描述了所有相同種類的元素所普遍具有的方法和屬性。一些接口繼承自 Element 并且增加了一些額外功能的接口描述了具體的行為。
例如, HTMLElement 接口是所有 HTML 元素的基本接口,而 SVGElement 接口是所有 SVG 元素的基礎。大多數功能是在這個類的更深層級(hierarchy)的接口中被進一步制定的。
探討
查資料的過程中我發現,關于getElementById和querySelecter在MDN和ts的規范并不相同。
- ts中
let res =document.getElementById('test'); //HTMLElement let el = document.querySelector('# test'); // Element
- mdn中
querySelector,getElementById兩者均返回Element。
以上就是typescript基本數據類型HTMLElement與Element區別的詳細內容,更多關于TS類型HTMLElement Element的資料請關注其它相關文章!
原文地址:https://juejin.cn/post/7160287639059300382