ts有而Es6沒有的
# 那些TypeScript里有而ES6里没有的
# 强类型
这是TypeScript里最吸引我的地方,毕竟很多的bug都有由于类型引起的。
const name:String = "Hello World"
1
TypeScript里也有现代语言都具备的类型推断特性(Java要10以上的版本),不需要每一个变量都声明类型。
# 支持联合类型
避免限制的太死,用或的关系放开
function padLeft(value: string, padding: string | number) {
// ...
}
function getSmallPet(): Fish | Bird {
// ...
}
1
2
3
4
5
6
2
3
4
5
6
# 元组
感觉略有些鸡肋,不过像一些现代语言确实提供了该项功能,比如Swift。
let x: [string, number] = ['hello', 10];
1
# 枚举
更像后端语言了。
enum Color {Red, Green, Blue}
1
# 特殊类型
- any
- void
- never
# 接口
TypeScript里的接口从约束的角度看类似于Java后端语言里的接口,它还能针对对象字段。
interface LabelledValue {
label: string;
}
function printLabel(labelledObj: LabelledValue) {
console.log(labelledObj.label);
}
1
2
3
4
5
6
7
2
3
4
5
6
7
也能支持可选
interface SquareConfig {
color?: string;
width?: number;
}
1
2
3
4
2
3
4
另一个功能是约束方法,跟Java里一样。
还能支持索引的约束。
interface StringArray {
[index: number]: string;
}
let myArray: StringArray = ["Bob", "Fred"];
1
2
3
4
5
2
3
4
5
# 类的Field支持修饰符
class Demo {
private a: string;
public b: string;
protected c: string;
readonly name: string; //相当于Java里的final,在初始化或构造函数里一定要被初始化,至多赋值一次
}
1
2
3
4
5
6
2
3
4
5
6
# 支持抽象类
abstract class Animal {
abstract makeSound(): void;
move(): void {
console.log('roaming the earch...');
}
}
1
2
3
4
5
6
2
3
4
5
6
# 函数也有类型
像Java里的Lambda
let myAdd: (x: number, y: number) => number =
function(x: number, y: number): number { return x + y; };
1
2
2
# 函数参数支持可选
其实typescript里的函数参数都是可选,只是TypeScript禁用掉这个功能后,可选参数就编程了特性。
function buildName(firstName: string, lastName?: string) {
if (lastName)
return firstName + " " + lastName;
else
return firstName;
}
1
2
3
4
5
6
2
3
4
5
6
# 支持泛型
# namespace
像是以前把许多变量或方法挂载到某个对象下的用法,只不过可以分离到不同的文件里去,是模块化的延伸。
//Validation.ts
namespace Validation {
export interface StringValidator {
isAcceptable(s: string): boolean;
}
}
//LettersOnlyValidator.ts
namespace Validation {
const lettersRegexp = /^[A-Za-z]+$/;
export class LettersOnlyValidator implements StringValidator {
isAcceptable(s: string) {
return lettersRegexp.test(s);
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 支持装饰器
ECMAScript2015中还没对装饰器支持,标准也没有最终定案,不过一些插件还是对它进行了支持。TypeScript里原生支持,Angular里的一些声明都是用装饰器实现的。
# Mixin
Vue和早期的React都是有Mixin的,TypeScript里其实没有Vue里声明一下就行那么爽快。
# 三斜线
用于声明文件的依赖。
/// <reference path="..." />
1