这两天终于抽空学习了typescript,把欠了四年的帐给补上了。
废话不多说,先上官网链接:TypeScript中文网 · TypeScript——JavaScript的超集
一、下载安装:用npm
> npm install -g typescript
验证是否安装成功:
> tsc
二、介绍一些概念:
TypeScript是JavaScript的超集,是在JavaScript上添加了静态类型定义而构成的。
静态类型:定义变量时需要说明类型,并且类型不可变。
动态类型:定义变量时不需要限制类型,可以给变量赋任何值。
JavaScript支持的类型:string,boolean,number,bigint,null,undefined,symbol,object
三、语法:
定义变量和方法:
let taskName : String = "work as bee";
let createDate : Date = new Date();
let taskNo : number = 1;function addTask (name : String) : object {return new Object();
}
定义变量为任意type:
let test : any = "test";
test = 1;
定义接口:
interface Task {name : string;createDate : Date;no: number;
}function getTaskByNo (no: number) : Task {return null;
}
在接口中定义可选参数和只读参数:
interface TaskEnhancement {name : string;createDate : Date;readonly no : number;content ?: string;
}function addNewTask (task : TaskEnhancement) {}
定义枚举值:
let testType : "typeOne" | "typeTwo";
testType = "typeOne";
自定义type:
type cost = number | string;
let opTest : cost = 100;
if (typeof opTest === "number") {let testN : number = opTest;
} else {let testO = opTest;
}
js转换为ts:给所有的参数加上type,所有function的返回值加上type
class的权限:private,protected,public(default)
泛型:
function clone(source : T) : T {return Object.assign({}, source);
}interface KeyValuePair {Key : TKey;Value : TValue;
}
四、tsconfig.json
支持JavaScript:allowJs,checkJs
添加其他库:lib
{"compilerOptions": {"target": "es2016",/* JavaScript Support */"allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */"checkJs": true, /* Enable error reporting in type-checked JavaScript files. */"lib": ["ES2015.Promise", "WebWorker", "DOM"]}
}
五、添加第三方件
在网站npm上搜索typescript支持的第三方件,使用npm安装,在到node_modules目录下找到对应的三方件。例如:
搜索@Type jquery
安装: