类型
布尔、数字、字符串、数组、
元组Tuple:let x: [string, number]; 对应位置值类型有要求,跨界的值类型为联合类型
枚举:为一组数值统一命名,enum Color {Red = 1, Green, Blue};后续值依次增加,如果第一个不为数字,后面的会undefined
Any: 可选择性的包含或者移除类型检查
Void: 没有返回的函数类型
null 和 undefined:所有类型的子类型,通过开启—strictNullChecks 检查非空
Never:抛错、没有执行结果的函数
Object : 非原始类型
类型断言:
变量声明
作用域:var 的变量会享受函数内部的整个作用域(即作用在自身块作用域外 和 for循环外) =》 使用 let
立即执行函数避免延迟调用的函数变量不能及时更新 =》 使用 let
let: 每次执行为变量创建新的环境
const 和 let的行为一样, 除了不能再次赋值,但可以内部修改
数组解构 、 对象解构
接口
接口的作用就是为这些类型命名和为你的代码或第三方代码定义契约。
类型检查器不会去检查属性的顺序,只要相应的属性存在并且类型也是对的就可以。
接通 object 和 function
readonly: 属性只读, ReadonlyArray
跳开检查:
1.索引签名: [propName: string]: any
2.赋值给变量: 因为只有对象字面量会被特殊对待经过额外的属性检查
函数类型: (source: string, subString: string): boolean;
可索引类型:支持 字符串 和 数字,且数字类型的返回值是字符串返回值的字类型
类类型实现接口: interface ClockInterface { currentTime: Date; setTime(d: Date); }
interface ClockConstructor { new (hour: number, minute: number): ClockInterface; }
interface ClockInterface { tick(); }
接口描述了类的公共部分,而不是公共和私有两部分。 它不会帮你检查类是否具有某些私有成员。
接口的继承: interface Square extends Shape, PenStroke { sideLength: number; }
继承类的话就只能由这个类的字类所实现
class Button extends Control implements SelectableControl { select() { } }
类
存取器:
get fullName(): string {return this._fullName;}set fullName(newName: string) {if (passcode && passcode == "secret passcode") {this._fullName = newName;}else {console.log("Error: Unauthorized update of employee!");}}// 只带有 get不带有 set的存取器自动被推断为 readonly
不能创建一个抽象类的实例
函数
函数使用函数体外的变量,称作“捕获”
剩余参数
function buildName(firstName: string, ...restOfName: string[]) {// restOfName is params[], 且一直到最后的参数}
顶级的非方法式调用会将 this视为window。 (注意:在严格模式下, this为undefined而不是window)。
箭头函数能保存函数创建时的 this值
this参数: 来自对象字面量的表达式,可以提供一个假参数this到参数列表最前面
functionf(this: void) { // make sure this is unusable in this standalone function }
函数重载:。。。
泛型
泛型类约束
interface Lengthwise {length: number;}function loggingIdentity<T extends Lengthwise>(arg: T): T {console.log(arg.length); // Now we know it has a .length property, so no more errorreturn arg;}// 使用构造函数的类 类型function createInstance<A extends Animal>(c: new () => A): A {return new c();}
