首先想说的是学习 TS 之前得先会 JS,因为是 TS 是 JS 的 superset。如同 C++ 是 C 的 superset 那样。另外就是这门语言没那么痛苦,增加的东西不是很多,这样学习曲线就应该比较平缓了。
最后因为我对 Angular 比较感兴趣,所以顺势而为地就把 TS 学习也搞上来了。
官网:http://www.typescriptlang.org/
安装
安装 nodejs 和 vsc,然后安装 npm install -g typescript
tsc -v 显示 ts 编译器版本
tsc --init 创建 tsconfig.json
tsc -w 监视目录自动编译
忽略错误
暂时没办法处理的错误,可以在报错一行上方使用 // @ts-ignore来忽略错误
// @ts-ignore
提示 Object is possibly ‘null‘ 的N种解决方法
参考:https://blog.youkuaiyun.com/iamlujingtao/article/details/110573421
理解 namespace
https://blog.youkuaiyun.com/caseywei/article/details/104657987
其实如果你的项目直接是用ts写的可能用不上namespace, 毕竟export就可以产生模块, 模块天然就有隔离分组作用
约束 map 类型
//key为string , value为number
var map: { [key: string]: number; } = {
"t" : 3,
"o" : 5,
"g" :10
};
for(let k in map){
egret.log(map[k]);
}
this 类型
函数中 this 如果不明确类型会报错,我们需要指定一下。Js 的 this 其实也是一个隐藏的参数,于是 ts 中要声明其类型,直接做法就是把它作为显示参数,例如,
getName(this: Obj): string
但实际编译后的 js 不会出现这个 this 参数。
函数签名
函数类型是 Function,但是这个太笼统,完全看不出有哪些参数及其类型,和返回类型,于是可以有函数签名
/**
* 加载脚本
*
* @param url
* @param id
*/
export function loadScript(url: string, id?: string, cb?: (ev: Event) => any): void {
var script: HTMLScriptElement = document.createElement("script");
script.src = url;
if (cb)
script.onload = cb;
if (id)
script.id = id;
document.getElementsByTagName("head")[0].appendChild(script);
}
添加基础类型(prototype)的扩展方法
//声明接口,也是在声明date这个基础类型要定义一个format的扩展方法,不写接口声明会报错
interface Date {
Format(fmt:string):string;
}
//要写到class类的外面,不然会划红线报错
Date.prototype.Format = function (fmt) { //author: meizz
var o = {
"M+": this.getMonth() + 1, //月份
"d+": this.getDate(), //日
"H+": this.getHours(), //小时
"m+": this.getMinutes(), //分
"s+": this.getSeconds(), //秒
"q+": Math.floor((this.getMonth() + 3) / 3), //季度
"S": this.getMilliseconds() //毫秒
};
if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
for (var k in o)
if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
return fmt;
}
语言特性
比较 js,TS支持类 Class、接口 interface、泛型 Generics 这一堆高级的 OOP 特性。这样广发熟悉 OOP 的开发者就可以徜徉在现代化软件思维中~
除了官网,推荐这里的教程:https://basarat.gitbook.io/typescript/