涉及代码仓库
安装
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中,通过document.getElementById()返回HTMLElement类型,而document.querySelect()返回Element类型。
那么两者区别是什么呢?
Element 是一个通用性非常强的基类,所有 Document 对象下的对象都继承自它。这个接口描述了所有相同种类的元素所普遍具有的方法和属性。一些接口继承自 Element 并且增加了一些额外功能的接口描述了具体的行为。
例如, HTMLElement 接口是所有 HTML 元素的基本接口,而 SVGElement 接口是所有 SVG 元素的基础。大多数功能是在这个类的更深层级(hierarchy)的接口中被进一步制定的。
查资料的过程中我发现,关于getElementById和querySelecter在MDN和ts的规范并不相同。
let res =document.getElementById('test'); //HTMLElement let el = document.querySelector('# test'); // Element
querySelector,getElementById两者均返回Element。