类型化数组
const arr = ['Kobe', 'James', 'pierce'];
const arr: string[] = ['Kobe', 'James', 'pierce'];
数组取值类型推断
const arr: string[] = ['Kobe', 'James', 'pierce'];const player = arr[0]; // string
const arr: string[] = ['Kobe', 'James', 'pierce'];const arr2 = arr.pop();
容纳不同的值
const arr2 = [new Date(), '2022-2-2'];
元组
和数组类似的数据结构,每一个元素代表一个记录的不同属性
const pepsi: [string, boolean, number] = ['brown', true, 35];
类型别名
const drink = {color: "brown",carbonated: true,sugar: 35}type drink = [string, boolean, number];const pepsi: drink = ['brown', true, 30];
接口
创建一个新的类型,来描述一个对象的键值。
interface Person {name: string;age: number;married: boolean;}const uncleMike = {name: 'Mike',age: 28,married: false}const person = (person: Person): void => {console.log(`姓名:${person.name}`);console.log(`年龄:${person.age}`);console.log(`婚姻情况:${person.married}`);}person(uncleMike);
接口的使用
interface Reportable {summary(): string;}const uncleMike = {name: 'Mike',age: 20,married: false,summary(): string {return `名字:${this.name}`}}const drink = {color: '棕色',carbonated: true,sugar: 35,summary(): string {return `这个饮料的颜色是:${this.color}`}}const printSummary = (itme: Reportable): void => {console.log(itme.summary());}// 对象不符合接口就不能使用这个函数printSummary(uncleMike);printSummary(drink);
类
class Person {scream():void{console.log('hahha');}sing():void{console.log('lalala')}}const person = new Person();person.scream();person.sing();
继承
class Person {scream(): void {console.log('hahha');}sing(): void {console.log('lalala')}}class Men extends Person {sing(): void {console.log('Man-lalal')}}const men = new Men();men.scream(); //hahhamen.sing(); //Man-lalal
修饰符
public:这个方法能够在任何地方被调用private:这个方法只能在当前这个类的其他方法中被调用protected:这个方法能够在当前这个类的其他方法或者子类的其他方法中被调用 | 修饰符 | 当前类 | 子类 | 实例 | | —- | —- | —- | —- | | private | ✅ | | | | protected | ✅ | ✅ | | | public | ✅ | ✅ | ✅ |
对象初始化
class Person {name: string;// 规定初始化值传入的类型constructor(name: string) {this.name = name;}}// 实例化后,传入初始化实参const person = new Person('Tom');console.log(person.name);


