Interface:接口完成
- 用来定义对象的类型
Generics:泛型
泛指的类型
function join<T>(first:T, second:T) {
return `${first}${second}`
}
join<T>('1', '2')
function joinTwo<T, P>(first:T, second:P) {
return `${first}${second}`
}
joinTwo<number, string>(1, '2')
Classes:类
Enums:枚举类型
enum Status {
OFFLINE,
ONLINE = 4,
DELETED
}
// 0 4 5
console.log(Status.OFFLINE) // 0
console.log(Status[4]) // ONLINE
联合类型
- function fn(string: Dog | Cat)
联合类型类型保护
- typeof
- in
- instanceof // 只能使用在class的情况下使用
- 断言:(animal as Dog).wang()
ts-node
build : ‘tsc -w’
start: ‘nodemon node ./build/crowller.js’
concurrently:并行执行
tsc —init:创建tsconfig.json文件
配置文件及TS命令
tsc 命令会根据 tsconfig.json配置把文件下所有的ts文件进行编译为js
tsc demo.ts:只是编译一个文件,不会根据tsconfig.json配置进行
ts-node demo.ts:这个工具会使用tsconfig.json配置进行编译
exclude:排除需要编译的文件
include:包含需要编译的文件
namespace
类似于模块化的开发方案,避免所有的类成为全局变量
///<reference path="./components.ts"> 标注引用外部的命名空间
namespace Home {
class Header {
constructor(){
const ele = document.createElement('div')
ele.innerText = 'This is Header'
document.body.appendChild(div)
}
}
export class Page {
constructor(){
new Header()
}
}
}
new Home.page()
函数重载
- 函数可以通过传递不同的参数进行重载 ```javascript interface Jqueryinstance { html: (html :string) => Jqueryinstance }
declare function $(params: () => void) : void declare function $(params: string) : { html: (html :string) => {} }
// 使用interface语法实现重载 interface Jquery { (readyFunc:() => void): void; (selector:string): Jqueryinstance; } declare var $: Jquery ```
如何学习TS
- 任何变量都声明类型
- 不到万不得已不要用any
- 给你的对象声明接口