类型化数组

  1. const arr = ['Kobe', 'James', 'pierce'];
  1. const arr: string[] = ['Kobe', 'James', 'pierce'];

数组取值类型推断

  1. const arr: string[] = ['Kobe', 'James', 'pierce'];
  2. const player = arr[0]; // string
  1. const arr: string[] = ['Kobe', 'James', 'pierce'];
  2. const arr2 = arr.pop();

容纳不同的值

  1. const arr2 = [new Date(), '2022-2-2'];

image.png

元组

和数组类似的数据结构,每一个元素代表一个记录的不同属性

  1. const pepsi: [string, boolean, number] = ['brown', true, 35];

类型别名

  1. const drink = {
  2. color: "brown",
  3. carbonated: true,
  4. sugar: 35
  5. }
  6. type drink = [string, boolean, number];
  7. const pepsi: drink = ['brown', true, 30];

接口

创建一个新的类型,来描述一个对象的键值。

  1. interface Person {
  2. name: string;
  3. age: number;
  4. married: boolean;
  5. }
  6. const uncleMike = {
  7. name: 'Mike',
  8. age: 28,
  9. married: false
  10. }
  11. const person = (person: Person): void => {
  12. console.log(`姓名:${person.name}`);
  13. console.log(`年龄:${person.age}`);
  14. console.log(`婚姻情况:${person.married}`);
  15. }
  16. person(uncleMike);

接口的使用

  1. interface Reportable {
  2. summary(): string;
  3. }
  4. const uncleMike = {
  5. name: 'Mike',
  6. age: 20,
  7. married: false,
  8. summary(): string {
  9. return `名字:${this.name}`
  10. }
  11. }
  12. const drink = {
  13. color: '棕色',
  14. carbonated: true,
  15. sugar: 35,
  16. summary(): string {
  17. return `这个饮料的颜色是:${this.color}`
  18. }
  19. }
  20. const printSummary = (itme: Reportable): void => {
  21. console.log(itme.summary());
  22. }
  23. // 对象不符合接口就不能使用这个函数
  24. printSummary(uncleMike);
  25. printSummary(drink);

image.png
image.png
image.png

  1. class Person {
  2. scream():void{
  3. console.log('hahha');
  4. }
  5. sing():void{
  6. console.log('lalala')
  7. }
  8. }
  9. const person = new Person();
  10. person.scream();
  11. person.sing();

继承

  1. class Person {
  2. scream(): void {
  3. console.log('hahha');
  4. }
  5. sing(): void {
  6. console.log('lalala')
  7. }
  8. }
  9. class Men extends Person {
  10. sing(): void {
  11. console.log('Man-lalal')
  12. }
  13. }
  14. const men = new Men();
  15. men.scream(); //hahha
  16. men.sing(); //Man-lalal

修饰符

  1. public:这个方法能够在任何地方被调用
  2. private:这个方法只能在当前这个类的其他方法中被调用
  3. protected:这个方法能够在当前这个类的其他方法或者子类的其他方法中被调用 | 修饰符 | 当前类 | 子类 | 实例 | | —- | —- | —- | —- | | private | ✅ | | | | protected | ✅ | ✅ | | | public | ✅ | ✅ | ✅ |

对象初始化

  1. class Person {
  2. name: string;
  3. // 规定初始化值传入的类型
  4. constructor(name: string) {
  5. this.name = name;
  6. }
  7. }
  8. // 实例化后,传入初始化实参
  9. const person = new Person('Tom');
  10. console.log(person.name);