常用命令
全局安装Typescript命令
npm i typescript –g
查看版本号
tsc -v
初始化配置(解决TS和JS冲突问题)
tsc --init
自动编译
tsc --watch
发出错误
tsc --noEmitOnError 跟文件名
TS配置文件
"compilerOptions":{
"target": "es5", 将ts转换为es5
"module": "amd", 将ts模块化转换为amd模块化
"rootDir": "./ts", 将ts文件夹中所有ts自动转换 入口
"outDir": "./js", 将ts转换为js以后存在这个js文件夹中 出口
"declaration": true, 产生.d.ts文件,用来完成代码提示和使用
"declarationMap": true, 将d.ts和js文件关联在一起映射
"sourceMap": true, ts关联js的映射
}
数组定义方法:
type[] Arrray<type>
var arr: number[] = [1,2,3,4];
var arr: Array<number> = [1,2,3,4]; //泛型
var arr: [string, number, number, boolean] = ["1",2,3,true]; //元组,规定数组中每个元素;类型
any(尽量不使用)
不希望某个特定值导致类型检查错误
变量上的类型住注释
// 冒号+类型
let myName: string = "CHH";
TS不支持左边变量声明如:int a;
定义布尔类型时,小写是栈中的类型,大写是栈中和堆中类型。
var a: boolean = true;
var b: Boolean = true;
函数的定义
/ / 参数类型注释 返回值类型注释
function greet(naem: string’):void{
console.log("Hello," + name)
}
对象的定义
function printCoord( px: { x:number, y:number}){
console.log("坐标的x值为:" +pt.x)
console.log("坐标的y值为:" +pt.y)
}
printCoord({
x:3,
y:7
})
function print( px: { x: string, y?: string}){
//这个?是指可以传或者可以不传
}
联合类型(又称为union类型)
let id: number | string
//两个或多个其他类型组成的类型
类型别名
使用type给类型起别名
接口
使用interface加一个名字
interface Point{
x: number,
y: number
}
function perintCoord(pt: Ponint){
}
printCoord({
x: 100,
y: 200
})
拓展接口
interface Animal{
name: string
}
interface Bear extends Animal {
honey: boolean
}
const bear: Bear= {
name: 'wine',
honey: true
}
console.log(bear.name)
交叉拓展
type Aniaml{
name: string
}
type Bear = Animal & {
honey: boolean
}
const bear: Bear = {
name: 'winnie'
honet=true
}
类型断言
const myCanvas = document.getElementById("main_canvas") as HTMLCanvasElement
const myCanvas = <HTMLCanvasElemwnt>document.getElementById("main_canvas")
const x = ('hello' as unknown) as number
枚举
enum 加变量名定义枚举
enum Direction {
Up = 1,
Down,
Left,
Right
}
console.log(Direction.Up)
等值缩小
interface C {
value: null | number | undefined
}
function a(container: C, factor: number){
if(C.value !== null){
console.log("C.value")
console.value *= factor
}
}
a({ value: 6}, 2)
a({ value: null}, 2)
a({ value: undefined}, 2)
a({ value: '6'}, 2)
instanceof操作符缩小
function logvalue( x: Date | string){
if( x instanceof Date){
console.log(x.toUTCString())
}else{
console.log(x.toUpperCase())
}
}
logValue(new Date())
logValue("hello")
装饰器
使用时要设置experimentalDecorators为true