第三篇 TypeScript 【 typeScript 函数 + typeScript 数组 + typeScript 对象】

发布时间 2023-03-28 15:53:23作者: caix-1987

typeScript 函数

TypeScript 函数与 JavaScript 函数的区别
TypeScript 函数 JavaScript 函数
含有类型 无类型
箭头函数 箭头函数(ES2015)
函数类型 无函数类型
必填和可选参数 所有参数都是可选的
默认参数 默认参数
剩余参数 剩余参数
函数重载 无函数重载
箭头函数
1、未使用箭头函数
 
function Book() {
  let self = this;
  self.publishDate = 2016;
  setInterval(function () {
    console.log(self.publishDate);
  }, 1000);
}

2、使用箭头函数

function Book() {
  this.publishDate = 2016;
  setInterval(() => {
    console.log(this.publishDate);
  }, 1000);
}
参数类型和返回类型
function createUserId(name: string, id: number): string {
  return name + id;
}
函数类型
let IdGenerator: (chars: string, nums: number) => string;

function createUserId(name: string, id: number): string {
  return name + id;
}

IdGenerator = createUserId;
可选参数 及 默认参数
1、可选参数

function createUserId(name: string, id: number, age?: number): string {
  return name + id;
}

2、默认参数

function createUserId(
  name: string = "Semlinker",
  id: number,
  age?: number
): string {
  return name + id;
}

3、在声明函数时,可以通过 ? 号来定义可选参数,比如 age?: number 这种形式

4、在实际使用时,需要注意的是可选参数要放在普通参数的后面,不然会导致编译错误
剩余参数
function push(array, ...items) {
  items.forEach(function (item) {
    array.push(item);
  });
}

let a = [];
push(a, 1, 2, 3);
函数重载
1、函数重载或方法重载是使用相同名称和不同参数数量或类型创建多个方法的一种能力

2、要解决前面遇到的问题,方法就是为同一个函数提供多个函数类型定义来进行函数重载,编译器会根据这个列表去处理函数的调用

function add(a: number, b: number): number;
function add(a: string, b: string): string;
function add(a: string, b: number): string;
function add(a: number, b: string): string;
function add(a: Combinable, b: Combinable) {
  if (typeof a === "string" || typeof b === "string") {
    return a.toString() + b.toString();
  }
  return a + b;
}

为 add 函数提供了多个函数类型定义,从而实现函数的重载

3、在 TypeScript 中除了可以重载普通函数之外,我们还可以重载类中的成员方法

4、方法重载是指在同一个类中方法同名,参数不同(参数类型不同、参数个数不同或参数个数相同时参数的先后顺序不同),调用时根据实参的形式,选择与它匹配的方法执行操作的一种技术

5、类中成员方法满足重载的条件是:在同一个类中,方法名相同且参数列表不同

class Calculator {
  add(a: number, b: number): number;
  add(a: string, b: string): string;
  add(a: string, b: number): string;
  add(a: number, b: string): string;
  add(a: Combinable, b: Combinable) {
    if (typeof a === "string" || typeof b === "string") {
      return a.toString() + b.toString();
    }
    return a + b;
  }
}

const calculator = new Calculator();
const result = calculator.add("Semlinker", " Kakuqo");

typeScript 数组

数组解构
let x: number; let y: number; let z: number;

let five_array = [0,1,2,3,4];

[x,y,z] = five_array;
数组展开运算符
let two_array = [0, 1];

let five_array = [...two_array, 2, 3, 4];
数组遍历
let colors: string[] = ["red", "green", "blue"];

for (let i of colors) {
  console.log(i);
}

typeScript 对象

对象解构
let person = {
  name: "Semlinker",
  gender: "Male",
};

let { name:string, gender:string } = person;
对象展开运算符
let person = {
  name: "Semlinker",
  gender: "Male",
  address: "Xiamen",
};

组装对象

let personWithAge = { ...person, age: 33 };

获取除了某些项外的其它项

let { name: string, ...rest } = person;