Typescript 基础知识
Typescript 就是 Javascript 的超集,所以首先你要知道 Javascript 基础知识
类型注解
类型注解在TypeScript中是记录函数或变量约束的简便方法。
// 布尔值
let isDone: boolean = false;
// 数字
let decLiteral: number = 6;
let hexLiteral: number = 0xf00d;
let binaryLiteral: number = 0b1010;
let octalLiteral: number = 0o744;
// 字符串
let name: string = 'bob';
// 模板字符串,可定义多行文本和内嵌表达式
let name: string = `Gene`;
let age: number = 37;
let sentence: string = `Hello, my name is ${ name }. I will be ${ age + 1 } years old nex month.`;
// 字符串字面量类型
type EventNames = 'click' | 'scroll' | 'mouseove';
function handleEvent(ele: Element, event: EventNames) {
// do something
}
handleEvent(document.getElementById('hello'), 'scroll'); // ok
handleEvent(document.getElementById('world'), 'dbclick'); // 报错, event 不能为 'dbclick'
// 数组
let list: number[] = [1, 2, 3];
let list: Array<number> = [1, 2, 3];
// person参数必须是string类型,且必须有参数
function greeter(person: string) {
return 'Hello, ' + person;
}
var user = [0, 1, 2];
document.body.innerHTML = greeter(user);
// 类型报错
// 枚举
enum Color { Red, Green, Blue };
let c: Color = Color.Green; // 1
// 手动赋值
enum Color { Red = 1, Green, Blue };
let c: Color = Color.Green;
// 根据值得到名字
enum Color { Red = 1, Green, Blue };
let colorName: string = Color[2];
console.log(colorName); // Green
// 手动赋值的枚举项可以不是数字,需要使用类型断言来让tsc无视类型检查
enum Days { Sun = 7, Mon, Tue, Wed, Thu, Fri, Sat = <any>'S' };
// 枚举会被编译为
var Days;
(function (Days) {
Days[Days['Sun'] = 0] = 'Sun';
Days[Days['Mon'] = 1] = 'Mon';
Days[Days['Tue'] = 2] = 'Tue';
Days[Days['Wed'] = 3] = 'Wed';
Days[Days['Thu'] = 4] = 'Thu';
Days[Days['Fri'] = 5] = 'Fri';
Days[Days['Sat'] = 6] = 'Sat';
})(Days || (Days = {}));
// 任意值(任意类型)
let notSure: any = 4;
notSure = 'maybe a string instead';
notSure = false;
// 与Object类型区别
let notSure: any = 4;
notSure.ifItExists();
notSure.toFixed();
let prettySure: Object = 4;
prettySure.toFixed(); // Error
// 空值
function warnUser(): void {
alert("This is my warning message");
}
// 声明一个void类型的变量,只能赋值为null或者undefined
let unusable: void = undefined;
// Never
// never 类型表示的是那些永不存在的值的类型
// null 和 undefined 是所有类型的子类型。而 void 类型则不是。
元组 Tuple
元组类型允许表示一个已知元素数量和类型的数组,各元素的类型不必相同。
let x: [string, number];
x = ['hello', 10]; // ok
x = [10, 'hello']; // error
// 类型约束
console.log(x[0].substr(1)); // ok
console.log(x[1].substr(1)); // error, 'number' does not have 'substr'
// 访问越界的元素,会使用联合类型替代
x[3] = 'world'; // ok
console.log(x[5].toString()); // ok
x[6] = true; // error, 布尔不是(string | number)类型
类型断言
- “尖括号”语法
let someValue:any = "this is a string";
let strLength: number = (<string>someValue).length;
- as 语法
let someValue: any = "this is a string";
let strLength: number = (someValue as string).length
类型别名
用来给一个类型起个新名字。类型别名常用于联合类型。
// 使用 type 创建类型别名
type Name = string;
type NameResolver = () => string;
type NameOrResolver = Name | NameResolver;
function getName(n: NameOrResolver): Name {
if ( typeof n === 'string' ) {
return n;
} else {
return n();
}
}
解构
- 解构数组
let input = [1, 2];
let [first, second] = input;
console.log(first); // 1
console.log(second); // 2
let [first, ...rest] = [1, 2, 3, 4];
console.log(first); // 1
console.log(rest); // [2, 3, 4]
- 对象解构
let o = {
a: 'foo',
b: 12,
c: 'bar'
};
let { a, b } = o;
// 可以用没有声明的赋值,必需以括号括起来,否则{起始的语句会解析为一个块
({ a, b } = { a: 'baz', b: 101 });
// 使用...语法创建剩余变量
let { a, ...passthrough } = o;
let total = passthrough.b + passthrough.c.length;
// 属性重命名
let { a: newName1, b: newName2 } = o;
// 相当于
let newName1 = o.a;
let newName2 = o.b;
// 指示类型
let { a, b }: { a: string, b: number } = o;
// 默认值,属性为undefined时使用缺省值
function keepWholeObject(wholeObject: { a: string, b?:number }) {
let { a, b = 1001 } = wholeObject;
}
function f({ a, b = 0 } = { a: '' }): void {
//...
}
f({ a: 'yes' }); // ok
f(); // ok, default to {a: ''}
f({}); // error, 'a' is required if you supply an argument
展开
// 数组展开,展开操作是浅拷贝
let first = [1, 2];
let second = [3, 4];
let bothPlus = [0, ...first, ...second, 5];
// 展开对象
let defaults = { food: 'spicy', price: '$$', ambiance: 'noisy' };
let search = { ...defaults, food: 'rich' };
// 展开,只包含自身的可枚举的属性
class C {
p = 1;
m() {
}
}
let c = new C();
let clone = { ...c };
clone.p; // ok
clone.m(); // error
类
class Student {
fullName: string;
// 构造函数
constructor(public firstName, public middleInitial, public lastName) {
this.fullName = firstName + ' ' + middleInitial + ' ' + lastName;
}
}
interface Person {
firstName: string;
lastName: string;
}
function greeter(person: Person) {
return 'Hello, ' + person.firstName + ' ' + person.lastName;
}
var user = new Student('Jane', 'M', 'User');
document.body.innerHTML = greeter(user);
更详细的可以关注Typescript官网