7.1 TypeScript 函数与 JavaScript 函数的区别

TypeScript JavaScript
含有类型 无类型
箭头函数 箭头函数(ES2015)
函数类型 无函数类型
必填和可选参数 所有参数都是可选的
默认参数 默认参数
剩余参数 剩余参数
函数重载 无函数重载

函数定义

  1. function fn() {}
  2. const fn = function() {}
  3. const fn = () => {}

类型注解(两种)

  1. // 带参函数
  2. function square = (x: number ) : number => {
  3. return x ** 2
  4. }
  5. const total = square(3)
  6. // 另一种写法:函数参数接受解构类型。 即便只有一个解构时, 也需要遵循
  7. function square: (x: number ) => number = (x) => {
  8. return x ** 2
  9. }
  10. const total = square(3)

7.2 箭头函数

1.常见语法

  1. myBooks.forEach(() => console.log('reading'));
  2. myBooks.forEach(title => console.log(title));
  3. myBooks.forEach((title, idx, arr) =>
  4. console.log(idx + '-' + title);
  5. );
  6. myBooks.forEach((title, idx, arr) => {
  7. console.log(idx + '-' + title);
  8. });

2.使用示例

  1. // 未使用箭头函数
  2. function Book() {
  3. let self = this;
  4. self.publishDate = 2016;
  5. setInterval(function () {
  6. console.log(self.publishDate);
  7. }, 1000);
  8. }
  9. // 使用箭头函数
  10. function Book() {
  11. this.publishDate = 2016;
  12. setInterval(() => {
  13. console.log(this.publishDate);
  14. }, 1000);
  15. }

返回类型

返回:

  • 有返回
  • 无返回 void
  • never ```typescript // 注解形参和返回的类型 function add(a: number, b: number): number { return a + b; } const total = add(x, y) // total能够自动推断

// 函数没有返回值 function hello(): void { console.log(‘hello’); }

// never 函数永远不会执行到最后 function event(): never { while(true) {}; }

  1. <a name="gKfEq"></a>
  2. #### 参数类型
  3. ```typescript
  4. function createUserId(name: string, id: number): string {
  5. return name + id;
  6. }

解构参数:

  1. function add({a, b}: {a: number, b: number}): number {
  2. return a + b;
  3. }

7.4 函数类型

  1. let IdGenerator: (chars: string, nums: number) => string;
  2. function createUserId(name: string, id: number): string {
  3. return name + id;
  4. }
  5. IdGenerator = createUserId;

7.5 可选参数及默认参数

  1. // 可选参数
  2. function createUserId(name: string, age?: number, id: number): string {
  3. return name + id;
  4. }
  5. // 默认参数
  6. function createUserId( name: string = "Semlinker",
  7. age?: number,
  8. id: number): string {
  9. return name + id;
  10. }

7.6 剩余参数

  1. function push(array, ...items) {
  2. items.forEach(function (item) {
  3. array.push(item);
  4. });
  5. }
  6. let a = [];
  7. push(a, 1, 2, 3);

7.7 函数重载

函数重载或方法重载是使用相同名称和不同参数数量或类型创建多个方法的一种能力。要解决前面遇到的问题,方法就是为同一个函数提供多个函数类型定义来进行函数重载,编译器会根据这个列表去处理函数的调用。

  1. function add(a: number, b: number): number;
  2. function add(a: string, b: string): string;
  3. function add(a: string, b: number): string;
  4. function add(a: number, b: string): string;
  5. function add(a: Combinable, b: Combinable) {
  6. if (typeof a === "string" || typeof b === "string") {
  7. return a.toString() + b.toString();
  8. }
  9. return a + b;
  10. }

在以上代码中,我们为 add 函数提供了多个函数类型定义,从而实现函数的重载。之后,可恶的错误消息又消失了,因为这时 result 变量的类型是 string 类型。在 TypeScript 中除了可以重载普通函数之外,我们还可以重载类中的成员方法。
方法重载是指在同一个类中方法同名,参数不同(参数类型不同、参数个数不同或参数个数相同时参数的先后顺序不同),调用时根据实参的形式,选择与它匹配的方法执行操作的一种技术。所以类中成员方法满足重载的条件是:在同一个类中,方法名相同且参数列表不同。下面我们来举一个成员方法重载的例子:

  1. class Calculator {
  2. add(a: number, b: number): number;
  3. add(a: string, b: string): string;
  4. add(a: string, b: number): string;
  5. add(a: number, b: string): string;
  6. add(a: Combinable, b: Combinable) {
  7. if (typeof a === "string" || typeof b === "string") {
  8. return a.toString() + b.toString();
  9. }
  10. return a + b;
  11. }
  12. }
  13. const calculator = new Calculator();
  14. const result = calculator.add("Semlinker", " Kakuqo");

这里需要注意的是,当 TypeScript 编译器处理函数重载时,它会查找重载列表,尝试使用第一个重载定义。 如果匹配的话就使用这个。 因此,在定义重载的时候,一定要把最精确的定义放在最前面。另外在 Calculator 类中,add(a: Combinable, b: Combinable){ } 并不是重载列表的一部分,因此对于 add 成员方法来说,我们只定义了四个重载方法。


  1. interface JqueryInstance {
  2. html: (html: string) => JqueryInstance
  3. }
  4. // 函数重载
  5. // declare function $(readyFunc: () => void): void
  6. // declare function $(param: string): JqueryInstance
  7. // interface语法实现函数重载
  8. interface JQuery {
  9. (readyFunc: () => void): void;
  10. (param: string): JqueryInstance;
  11. }
  12. declare var $: JQuery;

如何对对象进行类型定义, 以及对类进行类型定义, 以及命名空间的嵌套

  1. // new $.fn.init()
  2. declare namespace $ {
  3. namespace fn {
  4. class init {}
  5. }
  6. }