更多关于函数

函数是任何应用程序的基本构建块,无论它们是本地函数、从另一个模块导入的函数,还是类中的方法。 它们也是值,就像其他值一样,TypeScript 有很多方法来描述如何调用函数。 让我们学习如何编写描述函数的类型。

函数类型表达式

描述函数的最简单方法是使用函数类型表达式。 这些类型在语法上类似于箭头函数:

function greeter(fn: (a: string) => void) {
  fn("Hello, World");
}

function printToConsole(s: string) {
  console.log(s);
}

greeter(printToConsole);

语法 (a: string) => void 表示 "a function with one parameter, named a, of type string, that doesn't have a return value"。 就像函数声明一样,如果未指定参数类型,则隐式为 any

请注意,参数名称是必需的。函数类型 (string) => void 表示 "a function with a parameter named string of type any"!

当然,我们可以使用类型别名来命名函数类型:

type GreetFunction = (a: string) => void;
function greeter(fn: GreetFunction) {
  // ...
}

调用签名

LPAm84sFcsDIs31ItVzsGkg8Kpt6+C1Q0moFlq8lxp2n0u8PPk00VzLarqsQo58z8pksd2D2ZFjcDbc2XZd5TpZi6JYGgXnaSUYuoAA937QO1qv3mVxu4JIATBdqJW1Gm+WoYm51Gxab7Coe2qCrtxpJkz2u+F/vOBx2t+MrBEIKmY26lscdH+ZTGxqiMw4+CTCem5rsXRNgfd1wJUQ3r1ale8naAhuVP/yBU9yeV/+uyWPkUgga5hy83HeddLoyOkGxqPxFx7TIlajx8KFwQfLZGgvbyMOhiY3EgD4LTUADGwO/Qwwy3M++R0tzb1yo

type DescribableFunction = {
  description: string;
  (someArg: number): boolean;
};
function doSomething(fn: DescribableFunction) {
  console.log(fn.description + " returned " + fn(6));
}

IDo6Ng3G2wWnzkUV+MOhY6JUOWTAdgHbPw5s9g/8PN6tVUM/IMdEPZH23x9jKQdWzEJzWU08adRy5EJHnrOBrEQqFG9J3Bz273CGC14gi5l1yOGqjUNHF517PWOmR2MndzVEV4vB4uek80Ki0QKy4LHJ9AnCrCQwa2EQMMxpE6JJ0kwwpS8LIqvfI4s64V4Ppavlar0EQAPBvHjiUs15Qg==

构造签名

zAefCVIR5fPqkyxl1AXlaX35S8YZ+UEzdArbHQt0Ywv1nkp/QJwHdQR72vGFrswRoWrb1/GcOdZuPAalR6LpyO1hojzpOyKAUq3PkW8RPX4URRB3bzLD6psuj7DKcetsUsGcoiszV4svczlk8NvKVvWu+Q97JAvyVQ25EMdQLaka9ky7W58uk+Mm9IZkc4fATRLxTgMQj5WT3sQ6GXgrcIBJKrwPANNIRxR7U+0iE3vfwHn+KuLNkXLGExJAWMqg1WbfIbEt4Uf7hT2PjcyoIQuGVCi5FgesVe5JjosJzlbqDmmYf7kwG0fKLWfnFtgxudbIASCMBFbXKFeVRPtGvg==

type SomeObject = any;

type SomeConstructor = {
  new (s: string): SomeObject;
};
function fn(ctor: SomeConstructor) {
  return new ctor("hello");
}

aBdxZg6gJksIjQoT7Lup/ag5eppGUES4d99nnlLlp/bgcvHQX1uTKY0nitZs5A3HIA8M0H+QKxDJEUa/0EDJJSlijLL+bM1EsIS4nVSn+MA5jrAG7tQ8mDo4ULfANGRZMifkX0KxYN3NP09rUsffmDwrQM48RKgEKeeokexrGknZdQaUpj4HZzSmFsXLZAxkwYL5KInDGjNW9FanBzzlkZGPlccI/tDkU05BkImDGQL/mxSKGVrsuJwuBSVBJ2sj

interface CallOrConstruct {
  new (s: string): Date;
  (n?: number): number;
}

通用函数

p0SJ3PKs2C+FUMEwkueUR5AhrFlSQQPV0okE1ROQ6exu8vBlRQnq7pkUZxI0OuwM84Ey8RZ4MKwspjG931DPoUM3BGHnNjSVV2Q5CbJJZyNJqIUusUTp54ehM39TLzH2wIb+lBtvyZxN0aN6/NSyoHhfYgxJa5eJsn13HC3MEQMakQnHc4OeF+U+i7h7M37VS+z9OXUP+2T3K7a/9SNi0L/cnZIS33P00tlEx3cJhgTaT5Lhql4cy0N8pUNAz4HH

function firstElement(arr: any[]) {
  return arr[0];
}

Sw9ww7xvF/eozko/mMZnXqDrwOfCMkT6nT3+YTj1rAERAxbdVjsUlvGnKt4L6GhGwhIAdy3EzYHp36Qvu/XOxXJrvcoNyrBZO2S44S+akVGq6ei8gQMa53vTW5PGhj5sEk6Sc1I8bHYi6a1l6HROPi4/nRnIjgb37IkMFVL4/j55wQp+N7p0Nti4qhS08yby

6Cs0qPMIls4lyEexk5i2ZceIgHtt0X2XKzl8SyOAj5T6F4sZiV87g16Ca8rvoDtICFDW3iC6/wvmxsBxdxbsBKs6wBbxmTqjFzhtb5hFNmfnk2XyqTe0gCZ1N0EDCkiWfSdNnIbhTvDSO/I6UMXnXwAMJpCYJMPaL5dxfYJc0jyp8NuxbSiCTA1MDZz3/oFBKyDMEjl6K/s/jjoG+Cdrz/PO44Z6M4Twz2lTeER6DMs=

function firstElement<Type>(arr: Type[]): Type | undefined {
  return arr[0];
}

pH893rh+4r7YzB19RPDv3pCFuZKF56xvNji3Os1d5J60IeSkiTuSH/2M5DZhgh2XLFcUbc0QpIz0ToUsju1eEnNzLCgwp0wQgDrmbQSFa48TILQonb7MHg0I34WM0a1cXsBDRuKSV0bwGFH1dn1QX4li3ul2H/erBhrsHrmb1GUEvr9IQEHhrzKGIN1b6YuLZM1WXIZGRXjyLsfSXWikJ2RxhxkqZLWykc52zIZ8WJKNbDQnde5ym/Tcsysr9Mg6ZJBRGLihVBkZuFrlfmMfphoznMc87RMCYmuOHiW7fVUU+wRC9EQIMcZDZK7pLfeS1xF4AN/u9keIbV4YxZVhgg==

declare function firstElement<Type>(arr: Type[]): Type | undefined;

// s is of type 'string'
const s = firstElement(["a", "b", "c"]);
// n is of type 'number'
const n = firstElement([1, 2, 3]);
// u is of type undefined
const u = firstElement([]);

推理

9L+smkaSjFgNjkVpzEOw4y/IAQkoQMOzpdQgUVVUcGYQ5W4cBkpBZ1GxMajqqKPtaD3NNuqO7ydoofFZLPOccexqbVbeajqKHBrQ4K2KrSAvfV5AHLosGaAnXlXt/ZbpdoMDK5aRCqokThITUgXGU78xfeMiDNk1NpEgkha7/+0=

tK1NjGJCXp5uZajB7b+JdQ0Yp2dODDOWv0qNrGn0SUeWYmuw9j3MnWChn48YFkxqSL/yL1o1Gw/5fv3LwR3diI7j2z16ftzdyvV5hz5RcwT20NiACUDrxjqlKpH4qMRSpUVv3wuBKRStwCj2YcoQ+w==

// prettier-ignore
function map<Input, Output>(arr: Input[], func: (arg: Input) => Output): Output[] {
  return arr.map(func);
}

// Parameter 'n' is of type 'string'
// 'parsed' is of type 'number[]'
const parsed = map(["1", "2", "3"], (n) => parseInt(n));

hGrYJ7EJPELFSApMSZJTiDZ80Ngm+cK13nh6d94Yj+LIJ5tGadZ+wuNDHiBpbGnX/TLyiLvkeUOYsIai4nxe/xMFPrkejuyojb59JtRqQLhaz2Bq+6n8IcfiHmzUXjSUQBkQP1vf+9WUzcgIco1202nLhs/np5clHd055oVE6HGah85MsMjyb73vcjZ0rTKLC7hqOKLBvbJsJKX+D9aeCuthnNNhn6zzanyM7DMopS5nwBX25lcESu9jxWrJeTWwgX7+9lwlrWabfG++02oS9F6dMzsR1LHGpQTo4JxWbGXk9n5CNrR88l0GqN6J/vhC

约束条件

NRK6nNGVEdsoT6o/MEdwK5K5isrehuw3V+YNoso34xLHrZ4871w6SQZhvOl38AAIHnYKQbx1nO9TVFlelfSkHZUERUymQ99o7dCE822yyDKzCg9parsucwqw0VaoFJmncr/geFmqYTBpvUkvs6K7+BZYYaqjyCAF3g3LCy0ilFJis+gL7jd+iSEFrx+wVgfJJUe/wNNROxX7XPum7298hyGj2d22Jtx2ab6byd8qwTWut9Dm+oeoAHq2dfyaNoYqFz3IeLwiEt/3COOFAL1XwJWRS6kN84DexasIX2gpOHZjSSirkWvLdrP8cVOdk7yi+vt7OvfzFtucxwEj0GpBVQ==

dyOFuMb9lIZ6SoT1tF7YrAav+S4ZBPv0c9Ij/6VvrFTYQBBKK/ohb/xg5KNd7zbmTJIhpYxGMM6/UFXV+rqlFbhPr/ycVnybasjg7M51PsMob9LVxe1+oXOebHIMxBf3J5lRl/z7PJcsXRyTzIyQh6Snu6+NhO8HFt8PeBawwl0pd2z7MtNVdlwcnh94IENDyt85b23aVBUBUVh4BxH1mc7wEfc4qYy2pLdnn7vaL6rw4bZPG2BRidDVhpwXC+vtrEKkY+5nW3ZxPAsxLdHMRFLsJH5oqjNYluXesHMg4r4=

function longest<Type extends { length: number }>(a: Type, b: Type) {
  if (a.length >= b.length) {
    return a;
  } else {
    return b;
  }
}

// longerArray is of type 'number[]'
const longerArray = longest([1, 2], [1, 2, 3]);
// longerString is of type 'alice' | 'bob'
const longerString = longest("alice", "bob");
// Error! Numbers don't have a 'length' property
const notOK = longest(10, 100);

cUEN3ZUM1BIks0/CD6hK8+xPWCVkYiGHAVa1VxCjlHMNxXP3D8rKZpX0U/9lJL/Acj9gjmipnZabbHoAc3Lk15hRVSZwuyUQcIOQa2Fa6gxDSQT5M1C+g/ED/Wr27KLNg3Bcf8NAMY8104CTlIwFqO/Vv1gaN6yNeOQPVW0t8BYPKcjiGjsTrku3v6I/ug5ES+ycCROORrV8+EJpeCDRwBvb6SU7LSHWs4kNiBl4F3Y=

c5/fZHVWbF6PJ+9d5YybsDtEIaS2dYNcKIJASS+aG3CJb4xGvUDZrg5+xcS7qnARMcDxhxOSYIb+A62UAf+w12MW+vLwssKVapDQO90xH1JQC4E4AMAJAKy2aDVvkniw58Gvs37Ikx+sK4P0zxxsx7pjZQ4PJggfcmfoX6owUf08YUkRo00Hai108ZCHR8+Q2924ybiDNKGexUh0vOlNSFs6uc9X7M9+8/Yoecf5samaKGkmgYbG3qQm0QdMZWVktvvL/Z4QMf10d7oH8yA8CMqqK40tdIXxEFWv2XW8ShQ6GOpVVALVhl79DdGJQdQaV/wnU8K2i2+IRdLPzAOrunCBZLUBi7EYhx8ihKWeXTa/C6GgZODb8LAm117Cg1rXv19IegSSK6cW96wDxAe0Yw==

c6EPQBjgqtoXHKYhy0PZqL5GEKd6C0nAK4O72/1wpeM4umNktjfmVMvxKR4XYoLnOViokOv0tQ8l2a367z2H4sechZaYtLmSVYJxLxrM9obMsjFeuo/BvqMDwWKhrgzGRr5g0wC1s9bgT5AurCM2hw5h3BuBVPmyXYX3EtR5aq2Z4Kr/h2wYYF/Ri85GecLhmNQUVxYicvILbuJfL4rp0VY3SsKIIGPAY9Pe+YwDwqyGP5a8J1nBBr2VfiyDslwz

Jwj4HK1YdG6g2JXfqsTkf/15N1xcyax8duznH/nVmNYBQxMiw1ix2kbZ0I7t3im2r9Rzja70aw/AybdLSca+JCfXI/vyU5rkCfUSA7TyJ8iHSYiFQ79bPl0GmRDgTjfQBAM3maZ7XhH0IAN2owVj9l0WJNsa61+iqhO9TEh7yCZtyfJ/rR1Utu2I3Dzev4oI01FzB+TkJd4X7SAkJX10IQ==

使用约束值

6HVKVJ2FqOQECcrCdcnLrVUz5OxWs7p1SJy4gIXTPC4ESCcFX/rq2lY1cL9Zb0cSmsSk90Y6EYJlguo0afPydg==

function minimumLength<Type extends { length: number }>(
  obj: Type,
  minimum: number
): Type {
  if (obj.length >= minimum) {
    return obj;
  } else {
    return { length: minimum };
  }
}

OJSoD1RY+3A/C0voNo6UWEAOYmOAua/5FSwXkAVFzpfZp8q/pv2WwjFQh/9COZASzaiTrh7JfDmotiNsJmG3oiWEynGPX4UEhticJnItJ0ewekBk6nVLgA9bgC+E/SkYOAU9yau7Kj0DHsQJ7sDgZjenP54SaeIznjEcYELrPNL8Jc9H39ukAFQWE5lNqCBtQImUfX1yDNmdbvC5Ju7wwFdo+GqnMS/9XtDDkqqsiYUwfjTfkJb36rz3JcLw6WvXDJN+HPTnAiH+GN/BELO/nMYFDDRO2eFv+s76yw7+KwLRMJtwbGbDFXxZlx7rAz0bdgtFNa0cUoeQOPA1gigmPE8KHQTh8w59WD9Xqu3XpZjvWq5qD4Ei+lZTg8jL3X+PiyN1VqisL/uIgyzca4mDOI4c4yeuMejkwYaeBawYScClQr5ptfyV2gDgmt4Tkz/UelvvyBejyjqLxyF3h0RXSdZYcV5qq34nfghCRH2k6ks=

declare function minimumLength<Type extends { length: number }>(
  obj: Type,
  minimum: number
): Type;

// 'arr' gets value { length: 6 }
const arr = minimumLength([1, 2, 3], 6);
// and crashes here because arrays have
// a 'slice' method, but not the returned object!
console.log(arr.slice(0));

指定类型参数

uQVbq/mkRP1gZCZZ0sWkb+0ok1RoDP53f4AjbLTaB1iDyAWBZnmObiDefJL7J5+q/GU+eyX54G+Z1cSwQMMHF6PfNaOlUsd4jxGcnHvc2IYWBQAwDzTvzf0x/ObgNuRzLctcSrhgtQBlHTjlSfpDp6vquedmy1xVbtO01gNOiuVfI32uBJObtOTYXarreyCdytP1ABdmiwpnlyoZVSvfDdIKy5UhRmMoFApAb6SVOik=

function combine<Type>(arr1: Type[], arr2: Type[]): Type[] {
  return arr1.concat(arr2);
}

3kIRZtEWznCTlOwEvbFrq/gz874hS3DXbKQLQhzHlMdmoG1p3W9aYfmUI4gPjtE0vZtMgvjlFxs5+x9U96QgQA==

declare function combine<Type>(arr1: Type[], arr2: Type[]): Type[];

const arr = combine([1, 2, 3], ["hello"]);

5IrFiYQT5qdRvihhSDKftmTCYQo/kAdKz3qV3GcqHpUTLeMF1wd0w8shbInI/R114z2Js+mm9oqM4Nuz7zxabbc/tiPw3zotnGRB9FIMEr8=

declare function combine<Type>(arr1: Type[], arr2: Type[]): Type[];

const arr = combine<string | number>([1, 2, 3], ["hello"]);

编写良好泛型函数的指南

p6JuyC6bUMynLAjkpVXVmcmVHTEB7PppsJMCxDsk56ZrO3WTURNuFX3sKQ3fTR5Am++v/aBH9kiHLVaPq08p/YZhSGAqLG/A2Y19XruJptpK1UA6S7ro0ohzXjBgP4VNPa6dWo5VF8EH8DaFbsmQLUnHqIiUwdmm4GQwSTYsweaMneniiyvvmIu210SdOt7dYZoYK7yPG3lNKJUtg42JnfQk2eO+GdGE8PrgCX1Vb3XWa6SH+um6WKXjPoH+rUT5SyHuuTZxyKdNsdx8rFaqyQ==

下推类型参数

RxXdqxHBoQZUXaWKbBusY96blQIu1+gz4v921GO7Zi6vn5lCrUaw8o2d0WCGPKZVoa7u3Ytr2vz+gOvKEN+S4w==

function firstElement1<Type>(arr: Type[]) {
  return arr[0];
}

function firstElement2<Type extends any[]>(arr: Type) {
  return arr[0];
}

// a: number (good)
const a = firstElement1([1, 2, 3]);
// b: any (bad)
const b = firstElement2([1, 2, 3]);

UcS74WnCfRR7TIzYP4eGLkTN3tQOFcVK+yObTLjPMwilzXFSzz98mAugq9vNDBvtMhqEtFTeNey+NtQyxmv91K6m0ZEoM28noAOZrmIvBAgOpbe5Xa2xd0aLU66IQ2CFTLp6yqZc/sm7Z0EcnASp2pOVjh5N9p3QALZQErULoi0ZH+gb77qMj2l+5aPkjQ3wJQzzIojS5qPZh7wBcmP/tp5zHcUThRH2XquAZmGF5wjws9HnoA/AYfCSZZ9Pob3eEr+Ruy4yOQOHp17OUgIlkB008oG1MichfGGBBqYI4mprKl0k0KwigPly/7DbJZCSvV314d4YyQ4aGiAoA55w3qvf4M8oXCCBk8GNO/xq0QLo+95HggcFUdWnVM7iOLeIvEkHbkB9DwO4MVgnLmQ9gvz9YbVfP2I5yZsgymM7oJ3usvZe02w1OnPjaFt+ewQdSW5yaB/emhTklXnEGvSJI39nFWYJxR1D7p3jYViNvzY=

6r+C22J021s8Rsb/YddZc7ulQPCgkj2e526LKuPq/AqXp7MwSo2Ntt0Xn06/IGCio3nFQi95bmHk33WXFjDdh7KemnCfoTUyraV4rtU0a34tUR3WyN57Sm/8W/jiDOxP

使用更少的类型参数

J9dALtDe/ltAMuWlH5bwDEbqBVsUsAgR4cM5LeTBesNWWjVpFOWSsEAKQgVjve8m

function filter1<Type>(arr: Type[], func: (arg: Type) => boolean): Type[] {
  return arr.filter(func);
}

function filter2<Type, Func extends (arg: Type) => boolean>(
  arr: Type[],
  func: Func
): Type[] {
  return arr.filter(func);
}

pUsg1nK6oVYT1zymRIFQ7G1KYe6qyPLP+E93smfmyntOJzVM8QucMwXZIy4GuRs2oD2JHMepzdMDR22LPr8fTzY2e1B1JjaIlGcnPOgEt5U9Bn+S4fEVwLQk82ZEkpv+eQbupBhv4ppp/uqVERC0ZT2O9bymzfS1GcuASWQ/W3AsDe1tSISUgmDWIrRNXtHyChVXpIIkaYam0G4R2rn0SRmZ28l+3IIxXHEyOcBjTP9flY6+FWfJh5gYUzOjAFf7nP4/S3+OslpSsOuwrp8VaYK9rirAQokbJKCchzoLPJiyBsczTd1mt4SKi+3U49M+7qxd3cl4MhcbmbTWdfFDBoheV+mBEtNJU6x5a95e26knRi+byxFoOyIbwkMTOGMCAYvaRWhKqNtyUfMK5u4fAQ==

6r+C22J021s8Rsb/YddZc8jI0zZLMGI+PVCcfehbh1UIU0gSgxsHPceUZ+ZOCGAQnAN4kEWh89WHC4JcUhOcKiBFmAHFdXTeSN5e8rspvOU=

类型参数应该出现两次

nJPXAVG8sLGf/6WjwNS441ngRBf/208BSkiJ5c8Hr6uwF/Cf1dkSSrORUpiiZykf5O0gNbrOHsvo92jXCMPs4w==

function greet<Str extends string>(s: Str) {
  console.log("Hello, " + s);
}

greet("world");

ivOyzJ2HffmaIJXb0QgAMwndgtrWSjtMiNwoanL0wHe+2iVM4I0WGo2BuIHJDbmmyaHG7NDiyNXLU8l81afrLQ==

function greet(s: string) {
  console.log("Hello, " + s);
}

MPqlX/mQupy48cxnHiSCxXtXDOg6dcU75JeogvfXeU7szwI8xoD7EjZX6Iu+/qcK2O7WjX5gqO5APfKPNlrCj1IldwM2a0VTywp63nOSOi4/XG9Grl2lzMtPGvbpu70zB2fT/SuBt8NCkr1C1IKPv4p63lDTlmmvTAi6nZvFdl7us8DNioKhEiyYXQnMX/XP9a7qQH4IIpkv6GxJjmBLLg==

6r+C22J021s8Rsb/YddZc7ulQPCgkj2e526LKuPq/ApIiTXtaCBV5azUQ1kZBXfb5kkGXkrPTskuREUSXPVX+virVbZY6Jbjnw7sFZNk5NWnkCExPVNesKC438n4VLRS4LORMcFafrNldDYRJ7SA+Ud2wjcc4wlrJhycgVFKnzE=

可选参数

iFb0exUNAES12YW5QAIUHsV65h0Pgv7ZcqC3uYYj1SDtdpmyyKL+AqjM+Qs2ZKUsdfS2nj+WVHe9f8BrA6GBY8gKLM+2s0Bbd8usN/P6wE7jDc+YZbRaqkFCKKzCMneoH0WsPXVS6vz/mLDOLEYewiW2OfJz2221MxqiXC8KdGKoRDpgclbfZFnfeuGuoilWK+V+4m0gkLPnsrkVPEJatw==

function f(n: number) {
  console.log(n.toFixed()); // 0 arguments
  console.log(n.toFixed(3)); // 1 argument
}

+/N+p609F3IOCW+dqUW/+Pxa17SYijX/5KT8Ow7nMifNxPJUpfYioz6RhfvBTMdrzrR+TNu5cAZENhk9rtS4QmGs1vlYuyF+Z+McK3JODgDRvQQzdJ/HCfu5lhftAoJ8Z1PtLVOpy7Gnw4dhKJhhfA==

function f(x?: number) {
  // ...
}
f(); // OK
f(10); // OK

kNZwR6TwBgnLe9isefg+RAWaLLwtLZP19jQnHcX//InACDgfp4gJHMKUMvdZR2Nc06HH418E9l91GJpFQ0tEVkoIC0V6HgK2KwMY33ZT+S1DZOYNRl6Xh/0qqs6Q95+qpck2Ez8SkmXWgKEDMUAKlQI8B9xYQUjrJdYusoXfj+oYiq8xVf8obrZGquiMCkpSeVZ9o0/y7C6rcbTc99FCw5aF+3tPFbYhuafKNwfNiE6nvmJ54SuhPRcjM6SPyGQdb7vcoNeRgcPnEDy4HpFjjFfWuHE9sjkh/M3Zbmu5MNw=

QOEL6SgQeAzGzpZjimADnt94BWYrvsd8ZFIo4Ni2PV/ETaY55Dxj1JJPfdUAFRHD

function f(x = 10) {
  // ...
}

NjYAJnPZLnwEq6QGQp38fE2TgL5DbsBdXviYsogk0dR7diEc3Sh3cnoBMPTDGh2yFSr1BZY5k9pHm15ZFleeC3FILTt+rQ5v/XbF22ij04MCjMBjZYjr9/8HVkBQjID2OWnnrL7f/WvjYqjueYuiMalqJs8p7FtLfiAfKogjSR28Z/98q6P7Z9n6Uh2qf8fk45ci2QM3nlsfihewuJeK6skn3F6pkCu/szPdvhigDSHUxlCui2+rTPalyEdXr8AFgV1rvmwXTKNtqHOFRLP+Zw41mpvlIc0E5u4a+8Q+kfnByWBMYCxALTPUTXjBgqmpHFaL35cYsH3DnF6EMSliKoyibJWC4cE4dQS8jyUkx3ZMUiPrKjdPX/kkYoIT5tGTDjCtQZf768WMfhnisLcns8os5liskzQq2TJaifPeI48=

declare function f(x?: number): void;
// cut
// All OK
f();
f(10);
f(undefined);

回调中的可选参数

Eq7JDG3IPjzPfoseHZQFgU1C4p6YYJWBpLfrYS+5+ZLo3nVKbridwqMo/ttx/z9cXygURxLlUNwk5rnjvcl2aGeMUrBMR+wK6CNiGZw0oHm9z1n6i2L5fGP4v0oJRY17OsSUeDwrf6Z0rKqsgwU1w+DR6qoIBZIYGNHjsHFTCHM=

function myForEach(arr: any[], callback: (arg: any, index?: number) => void) {
  for (let i = 0; i < arr.length; i++) {
    callback(arr[i], i);
  }
}

zVy8JXuv2PHkzdEvnHSVhDbTSBnRtAo7WIA4AMDyJF/91de9Aqz3B1f5OS4HZw+hYteky+7dgXI3SAjfluIs/al7o9LXjV/+lfXpr2gp4DKGziRop8GujqM+jInqpJH9L02y53olRzMGZL1B9+qOOk7fD9np3RVN7xqVrUEJYk0=

declare function myForEach(
  arr: any[],
  callback: (arg: any, index?: number) => void
): void;

myForEach([1, 2, 3], (a) => console.log(a));
myForEach([1, 2, 3], (a, i) => console.log(a, i));

3uhRE+VPjvSRouFqB/LKnXb2Ow18hsJ91HkBR9BYmhIT3U/nK/IS28/eIvvLPKgA6c93mAAU+fekk+meo1MFOofK+mmW+YttSPQtBQfmdjI4ewLK0uU7dSLH7kE7how37ISPZm1AaXJmxmJNoDkiSpWNiNaTjeoVchcdQv0yJHqkaANaZ/HYQhHRe1Mm5Yi8

function myForEach(arr: any[], callback: (arg: any, index?: number) => void) {
  for (let i = 0; i < arr.length; i++) {
    // I don't feel like providing the index today
    callback(arr[i]);
  }
}

l3F9aAYaE5kl4HixQnxY5tspwsXFZVIndFqIXrCR+rQGhAhojDOw/pV1xx9SCH52KSdp6y61Qa/GOsvgWvvrpLt9VjNGJ9bm/KRClMRzKn3XBbNn53+T3LWygCGnHOH+

declare function myForEach(
  arr: any[],
  callback: (arg: any, index?: number) => void
): void;

myForEach([1, 2, 3], (a, i) => {
  console.log(i.toFixed());
});

LPAm84sFcsDIs31ItVzsGvNojQmWWgdMGK44jzI7rPpPHQ6fZusgaju673FY3gUNLBO7xUMA/hR0hZb5BTC8yfwcjjTQkxQga8ymJDtlOkY+8QnSJpPiwn0LWhKBiGrBxLCdfNEauLGp2iq8n8C/Xl/BuxZtLEjAxhTyTcK2leJMTlEuUuhrJFKvLx+AJNWgw1h7MriEuq89e7fKbyQz9POtgU+TpFFSUMVTj8WfoeG0rEOz3ReD4N8zZeESd7UeCYdBHNz/V759M8Av94IFZ/mzw/KOfhkJ7z47ttXMBppLH3flIr4/6mDSbC3reDft

EF1KRQmkcOvyUnu31n0KBWux1uiGWkok87777BGqPzlwGzxrYKCbWUjt7f0UjLD4mNMW+Bbd3q9yEEGjrQOmLgDyIHqIWFoa2JFb8+zbDdwaScT0jnLHu2BW1rXUx7Esz0ajTuKSVMvJHmqILquBKQ2hkx2OShMBuGpr3iC26OBEl1sYOiZhyBqvy1hnLZce

函数重载

xrkRnjNpCVCy5Wg815VYv8qrNq7GD6jxa3Bpfck0+f7fglJgDiHSpfUD9GEwCtbxy/rRTpMvv/PS6EIauw4Bo//i0+MsReD3A1+F5KtnVvaEqvDSwbqfgzaa/kCDeCxZZiNNKr3uzK1uh9oNT03Y0r0KBnX+riCdRZf2OjF6KOL3FRupz6R+k6k0Q0Sma91jtBPJWO3AZ3qUlh98upuHPjAaNbsc6gupHIrr9YKkvE2fSx1qDCUt2ELcviBz5fnt2UeDqPBKjxkUizZqLRpuHX1vnXvslkC1l1a/kmiIMfo=

6Cs0qPMIls4lyEexk5i2ZQ+07N8G1vrHA9fcostfEcc2mcQlqIq0ConYJig5v1B/6IEE09NIzISGpC+L+0TjljtxVsZvNwG5l671fddvp7ZUR4PgfgjiR2JPgbOEGFYgnVbrnN4X4wKcYMLotz1Mjhna7V5S7S4Z0/JifLtv/bSKlmBfoX7wuNbXu3/F6SBxL3xl10MrdPjEcs/bHQcfsWsDRTTutOKuJsYeOyrdFs9soPQVchasxw3p0Er/PoH9aHWT0iGGy9YSZWuJRlu/Ll6BcGau8LUTU7MVJLaRBu8=

function makeDate(timestamp: number): Date;
function makeDate(m: number, d: number, y: number): Date;
function makeDate(mOrTimestamp: number, d?: number, y?: number): Date {
  if (d !== undefined && y !== undefined) {
    return new Date(y, mOrTimestamp, d);
  } else {
    return new Date(mOrTimestamp);
  }
}
const d1 = makeDate(12345678);
const d2 = makeDate(5, 5, 5);
const d3 = makeDate(1, 3);

cUEN3ZUM1BIks0/CD6hK80O9drk95Nra5RXSXPmnrlrOFqmMLwKZPAQo7Cu68ADERiQZT7MOEIqi2zUmh5pkWviiONt5hjZdBX243YLtDSB+tctbfU86MZ0X0pnYmhkwabjp+u0aT07nieO0V3hujZNjI6BvyMWLXa9aMvBzjhfEo2q1v4v/zHRpdEY1XKZL

Fso+/B+wfliCygTsUkdry3o3mYbw4mzhW3d9Rk2GSLIJ6IwsgWIx2F3wQL85QOu6pcclKqL2jHko8/HtKScATAbFaOw9twaI498aRVdbVomxagb+xdTXyDub2wrzXZbpvG2GV1RK+umyHPFJ6nWkNfhD2yidecbR2ApKgJsge2OFn2A8jFGxHY9gVDfJLUz9yWMLOlQ6KqXiX2CURKwWivcQIiEXn6tQEOG/r1/JDAo38LHYh0UDV9ORVhKW3U1czG3qJOuwm+XzNC3KoLCNGOMwcUf1cYSpEJCZpyTl07Fl/l2yGfrzSFH1kkTEIwr6RoxT58kMRUR7Yt0TFe6Ivs4nLTmU+UdO4Jd7+SCK3lg=

重载签名和实现签名

sI5ypnZemcnEzF/gW8sVmeOBJRZ/0uac5E18RbXcXQCENV3vlVxziDNlZuIQAWY0QyfE8MsmpXngX0hXIr0Z9WqL5X2yjChIQM2RxJV8YsO3dF7eXdyIbtmjMxw0vFODIgXdo5McxCr32fb7im/tlNL3F0XbaHj7O2nBGdrFtq4=

function fn(x: string): void;
function fn() {
  // ...
}
// Expected to be able to call with zero arguments
fn();

7j+ps9Ow68KWXZBXQSLWFeuWgc9o+O5zFlTJl2yKMT4W3ysGGugInmh4ruLgoe6RDuFAtfh82UAFdTKTkqRwfIWXnV1hnTbcyvAJ3c9TwuI=

8p0mQqKV9nSvoXKr3Ee5QkC369AeUvul9AcFXFdCqjm6hLiewh40tPNO7IGZWed+YmQp8AvanGcQE+IRLUl/AWdconK7ijx0MWc1mN6dbo9f+TDVcvH85eldFME8qPL485Qarwns+SNz/rhl8eciK3h45lUjAlccLtPzAxv0bEA=

xr2Dxt2xk5qcGPsx4gwRmYjbayYfPQKi5ep/ZH1sArVaztWFSgtTs0V/VrJEGYns/2eztKKenWuDiCWkcNR40gHT4PetSQbnWRmBkbbgGeaPioj3zNkpY2iDyIjI04laD+cntBOabgwek5PEvGbBtZzLcZ2i6amvA1gNwnYCnzSIzt/HOVtI/UkkCqto2uw8

function fn(x: boolean): void;
// Argument type isn't right
function fn(x: string): void;
function fn(x: boolean) {}
function fn(x: string): string;
// Return type isn't right
function fn(x: number): boolean;
function fn(x: string | number) {
  return "oops";
}

编写好的重载

q1gan77j0WzMcXOVAgWEwrZflQwAyjIWMQnOYrJqrdKF5XcDBzo0yofpH4MBACMy+9NYIqwMkt0EkGGFsSpfZb8KMzgDsmzdyG5rtXf7lG3/RrGYfmTxcLxnVOibyGhQn2KX3HmVnMccBptKs6904Oh2iNji14AlBz5vm/+spyS5UONb2plktR9zaOdnulL3OjX26C2Ko4yC54bFVQpeWiXOV0SS2xBdUXFPYAE2iJE=

nI+pUP61/yDUsiGwqlq5PpA1SXB2IVf6T44dcCe3mtOp0XMZVgQB7CZFKN2AzsZ31pR353Hz15BsAjRLjoLc9g==

function len(s: string): number;
function len(arr: any[]): number;
function len(x: any) {
  return x.length;
}

pRQp8Tqjt85CDCjtRWnAUdoDSGWYE7S0tuoENqg2QEhRxkmcYbSsUucU1YBNf+QBj5cASydG8HMYVdG+8Vsl+RiNqUt6hS17mmy8HhlWvWrixaHg/lDqPoOZtXl7vcXU+M7oYfVyqvjqKAYvAlkqmdrLoK+0gn/R/9bQRd1HRHrCYkPRiicZCDofJh76kMAIQYsuFL+H00GegT0YlsHmKkzEMyMu/NbSDIMrkWhNbJeBfkxDUjp1dnEn0Ihp7Krrh038WpSJXxY3kDnQOVQMTw==

declare function len(s: string): number;
declare function len(arr: any[]): number;

len(""); // OK
len([0]); // OK
len(Math.random() > 0.5 ? "hello" : [0]);

eYmci4rL9gcpj2LlHyyjFRs54V3/mPO2FDhXwLgeWK1Z3A5eqBQPimPWUHFB1hgcewBW9pbNTgMFIBvU8fR+tRSWrpxufCcAx72A4Dnf0Hs39m+Zf9XQA43nXF8l0ZyXvi0SwBiTKr34fqjZVZtF4+kOV3Nhp4aHGIUoA5dHkqg=

function len(x: any[] | string) {
  return x.length;
}

5TuqjMF2ZwH22BQldBmgjWsQmE0EB8IyRB7ljxhARxKPBZbtdOZQyLcTyaVHAFRp44J4r8rYYgXix/7EzAqJ8lM/Fz31JxM7a/2hn9Fms/Rlv6ilYACppShkn/4DMk9HVI3nSz1rdtaErK+BIfIRNHtnX13BNM6d6HTbyUSjav7hVsPGtrR02Zag06cKSH7Q

hpAancFt3oxgrOxj1IcG8DN2WN4Y9yxgjDBXJe9dSbWqYvlCvdHmHYsFUTJmv7wZhoOtILJA+cFHv59lRwPDlQ==

在函数中声明 this

pxeWF/mBX2pBMHeBsrg6jFhk3Zde5c362zSA/dfkorAC/qDnSGfBnACy1k2fxofTWaGpcpmQn4jqnaCTTn3nbVjk/w1EKTZi52Iq3oasmVAIhyM8yIo1a3C7VDvDbLUJ11GkKTg3K7o9NbDHFfjwJQ==

const user = {
  id: 123,

  admin: false,
  becomeAdmin: function () {
    this.admin = true;
  },
};

z75hFW6YQ9tzxgYHMGmKEAwQKNoI3dZfko9Q7CZfMsZ/l8r28aywLzxsQlzAA9IH+hBSLn5mJSVVtJOCrGgILeG8ExLi418cEO584gRxrxUd3pmHrm0I4kdougSSQQufryF6ksTbfIEJLyGxl1nQTeX30JYPNLe0oarpJzYZ+t7ulb6hAdDaLISRdv+dd82qrUgJ10T7XpKwXFbv+mBz7Go4pp12Ta8yZr6A7B6XPlBI5CoUXbc9uzZ+09PZoO9UFK5cTsGHUbIWITw25wWEtHG+fsvQKJyEmEzHxG+oBN0/XsupnuVFfqccjaI5WY7OgUGnadVS+H0T2lM+WVIDCJC1CUlln+IMR2NhUZV0QD06MQ8+KISHSQZArlvnmRTSrs4vk/lt3IMOEAQgW+GUvHsqUuQf85eobpU1nhBa1HyQyM28fc/ydmgLb7h+bxuS/uXwZkBVS2mhfCfNI5Cyr7YST/xmIH7WPPOeEQSvJ0q2n1f6F0vmkddsID9uzEGDUglWED//jLVCkfjzIQAePnSvQn7n9IWd3NZ2Vx6bVLCJ/oBe6qaBUaJMVjMmo6gzJ5aHofgnzbzaXymrhcFEFV0x6nR1xcTt/M2li6WKBYo=

interface User {
  id: number;
  admin: boolean;
}
declare const getDB: () => DB;

interface DB {
  filterUsers(filter: (this: User) => boolean): User[];
}

const db = getDB();
const admins = db.filterUsers(function (this: User) {
  return this.admin;
});

KPMY3+WhplemW6y3byy2WBxhJxvuQAHHj0BHUBZVwwlJAJQcXHfXfEXoue1DfZQvo7phZLv9qHrOVsCN/+QIVaTiobPErfYXNvzMaqJxIKoXO8gXuko/suJVgWfHacKRlTEDMY7FJpAh4MWJaVzfviojGCQLosk5b2OOfPgiEJL8vKZUWZ1NHQtXjqy2hTXzllH0FSnRQA+Z/ObiRPYjOD2TZhYS48xHWndIiVv1XIRzf+vBsRbdQB9dTHL0OqlvCmHTiQMHektQabjTNUFa9Q==

interface User {
  id: number;
  isAdmin: boolean;
}
declare const getDB: () => DB;

interface DB {
  filterUsers(filter: (this: User) => boolean): User[];
}

const db = getDB();
const admins = db.filterUsers(() => this.admin);

其他需要了解的类型

vvt4+2lcV3QZJEHgND6mvzqjDh04ZSqIdKEi+1bmZ7t+9dQ8oERJVaMnJTixfaHAF58PoOCsfJDr+X3K7l0t43eSr7VufhBbfHtREIRl5AdnoSz1pY4N9bReA+POrCKXwd8nndyJkPXCZhB3RpZMwv379TO+u0jOn305mGmurpZP04DjTyrPz1RZwlDyzOawNk6AoJY+N29haYZbSAA9+aGRGTyiUniDqeIPc+4fsMRusjKnlOE3sFsuv0e4MBja

void

O/gYsk7203MV+zJoKbBhNJCq/+fa1q2GUejdXPqT+kwZgid7CUhpYJoC++BeHMaRHcUvDcBT/pVD4ea9eaMwCGPlXXF11BNYX6jg2Htdqa+Ga3Wvan8SkoSUM/2OGHKAhuZym58AzbnP7NCJFRCGQp0jGtXXLNIdzoglGq9d8jMApU1BAKwAMXr8l0dMQqmElUXqQx/Uh7h5HFizARWDQDe+RtzyMnEPZiGdzJa58dPVTOaVaQV3hmCTyGAEVPZaSddqnYuNnQSbwo6q7lTqUw==

// The inferred return type is void
function noop() {
  return;
}

LPAm84sFcsDIs31ItVzsGns8vzGLHJQRWhS+/Mf/zq73uOACI00V2XG5tuS4Z+aevfkjsUl2RUlo/JwZZdNWcLPZO4O27hg71qR91YYngbPvPPo9zfomwQTRh6GrZ1OxwqVTNYMO6iCrrAaOa6nMDO8i1803yGhIFkl4imBMcZ7qjorhRNOOa/2Me/sG63A7G6Ztsivxg/c6QnJrOxzwkjK9TCGGuf9nZG2pEeG7wDoHthGcHw0fARxXIULI+g7sqsipg8ATb3CtHLw7XhwBmt0BYTCN4Y8ILjSAVdPq3YM=

O/gYsk7203MV+zJoKbBhNAysSf9/r9oAi31vrYfkqMJZACwFykYxV2tq35KvgE7BZWCPe72Eb676/z+7xIOBLA==

object

cUxP2f2AqMfN7+MVDefJ1lbLBeLm6ecLE0meaAfJfyAFGV1bsKGjqNFMz6Gkizyqkg11GOR/SmmjNYIXjay9TEB7kTbtTy8qTtHnBa+Y3tjn4qtTE4DfAERFL0kL5h4cr2T3osJDJgtuDXrI6rHXVARsbsN9JAtQG+1/twh5yT8OEmLE4ZJx46Viq5MFWsQ7/apchpHW2XfRJQ9c8BbPZzkP9GY1QXTSv77fDLchHnIbELIUp44iyNQZe0nnQIRfntlgLV9jv1XND586R5XxFRO37AujTNdjwJBGeT1YsrkduKNnfNER5jVNGqMGXPyufJQgY4lOvoJvCYIkgd3EcXO5zh1/sgUEHaKG09qyf29Z0+OR13ISsuah0h8OzV3O1EK9+zABfHpeRm24xup3KhFjfTn8g2ToNNHY1Ip583xiET/YzAMZGYKr7ltwgOsNgZ8AdE6TnJj5yz55BWY6tM07KH6t+Ghl2aRT2z9mKQ+qPO9SY3iYLe1CnxtIHTUq

A6R9h0XI2WS6IGfxO8BJh7JwjemYF8VLkenvfQisO67FXh+mfUy7TPtZ/Kapc7X7g4X4D3F/cnFyZTr5QvCzzPUzDbXfUpovDO5dIlQCMvlXjHWxjLxfOZURtEJ4dxjDtPvspTusPMRwAtougQRG+A==

UONSq0B8jo+Zm2UNHds4DcPtq3c9vjgObhZe8xzkNkRaywfWu89pBzNM88nxqHAYMlkAXl1P1fHlBhoFXxL7cIk3TeUG7MoSuT3vX4/OHxabszieed9BATINht0puUtwzRSHCzQ22qtJti/u+2YaMbZNtcEXvBjta1CqJ3/sgo6vFmIGClGq/KKXIrmVwcEN4AqNdJ8T86YM64mkLqRilUOS2fnG7xDbn/AiR9R5vRtGhzHG13KW8GSl9ARdGEuwDOQAVUiEU2bHPhDLj3hu8oXFbjJymJjozGpvKjK3lg/WdvB+aFkxSyZ+jOAJqFl8vnXEAfUc4ZBDKM7cIbCbAJ1ISFq+snhPjzXdPY6w34t/bxZOYcQO9UwukwbDO27K8dWslLctkLLf+hvV2UOgaSeg6ox5dMKKHASIbfQgXbQ=

unknown

/lHfZ4pUv2L77xPDy9CxAYdGrzM2pMn9Hpa+uiO7x/40lQCJl9wbRq0uJCBiwpBpgsqZclx6gDeUZ8ivYdwtfYTO1PqoAZl5bijeewlcGBIb9nl824QGazWg137N8WOEMElrpIKhLpgEKgTS1ex9911KdeLJSLolalq+iiLCpm45CiH2VDmdfwnIwH0lNkf4liY5ZcaCQiBca55VlgB+m9B+RyuYzRs7iBtYu5vySzk=

function f1(a: any) {
  a.b(); // OK
}
function f2(a: unknown) {
  a.b();
}

PDMeLFBcmPGQFOBwQJXsRkZKLFnzzGR8W0/708XkTylWL9svCMUA54LmDD//esVtZUlyz0KI1kt+qDPS5XHTpyephmCzW6+RGItPWuKP4IiSzrLu7umK57otYRZN0O9PrHb27BL5PE7fpJ0N9chtS/JVUXPSBnPMNrfM6s/x///I9iS5AY3tXRUy6xhUdDue

O1nyqC/SqpDgEZc/iE5EDwvVSPcGXSpcXCZzgNQm33UnrRnrTX6TT0bI4C7WevArA413g6yAMVBj2YloA4h5IQ==

declare const someRandomString: string;

function safeParse(s: string): unknown {
  return JSON.parse(s);
}

// Need to be careful with 'obj'!
const obj = safeParse(someRandomString);

never

CjMQQssTv/zg8IWO74cZjaDumyeFRxj/QgotAmsNo2I=

function fail(msg: string): never {
  throw new Error(msg);
}

p/rId9qIxZbyNOo1rDmw23Of9n2Yekzr5vbRJ1/e49gQWhFsWdjena+zODkW9/YVGYd+RmxNQkRS+76lvuQnq4/qpNrZaJaUfQMC9IIpOqVDVjW0eviNxiGd6ri/1fz7c442DLyFkcF0A8knvGv38yF3AG73Sq6pldVZxSlI+nqUoRqbP5TKb43NnmUPsfQ+

P3bXn85yiNBl99xbnQz7lrEINosIHh2WWntlPCZQs4EJHIwYx5RCgnC5IYZlYc4Oh+T9Xt37hgneabbpik7esYOt+zlqa+Vx9ml63e+yLDXL7ZyU7gHycQGX8xaD/yzm

function fn(x: string | number) {
  if (typeof x === "string") {
    // do something
  } else if (typeof x === "number") {
    // do something else
  } else {
    x; // has type 'never'!
  }
}

Function

erB8vnZwOW9It3HG5C21orlUDKuiXFUUgjZizEpbAFukmojXCHb6b2+ZFe3mJ9i2/Ul8hZQL2WQimfI69kHOl4PovNuPhGZQkIDdcqYVv60IIGwGkHCf6XzDEtwTfaftC8CKiBwsOOjjXT7oaVy2aInx6UAV0Lh5GWRSVVZDtIC2AsCp5kCP13KcdOMQUMwhihO70ZfGhvhWL6IMspbRuWsOGUiEMSeCNqmDbiYvUQl9bu5cgO3B1wN5nWmkpmuP44o/YKr07wLTGPfXL8b7l2dSRwUySXXWHr5UhbXyehkW4/ayrnGrGivGxUy1DGVu+jl//yhcFE/DrgMJrNU1puqu/Xi7qXZZVMUQA21ncICY7CM3ZHH+JdHrgRqW+u6Hbay3f9lFdZtfRcH9yr/fuZeH+yoTvP19sm2vdlNZfSI=

function doSomething(f: Function) {
  return f(1, 2, 3);
}

3LQrv36DYWOImBE0ppMQpY6fW+2avXYY7gNCU4GTyVaG9bF0ZmAS/7yWg05ZCfFym0NEpCHLZWJpgVMD7/SaTNzjxSaVKdehpHVwuBPtguK8jBbH3iud/Fv6qjsw8fpC+9jVdegBHX6jhbQo30/fEg==

qbdO9rYZzGdm7bDV3tqCqTHNKLnWtGZ44bDjnJ9Kuq7cQU0Z+c9FWSD0tX2Jh+BlnTV4Ys1jF1UxDM2m6alyt1Sx+udAA+kwegCkB0K52wNgsbeWyDOcrYzJ6wQJ0pruufwGL69/JwQbQHgdhkGT60wCsFN5/yiZn+IWWSS/c2I=

剩余参数和入参

剩余参数

JfpHBqdEKobTRijoOdl+zdFLbT1cAnGSasxPWSICcLsnfG4hosHIXJwrlL4nrlU5qmbPr1zTQ/BiNp0tfc8PjgDj7k2Mg42asp8G2u7G8fmqtdLYRDfzZFhbyBofgfSeDL4kU+A4a/CztZztQSfrd6PmM/+ItfXq1WCXzUwNSoOud8G98qwwiKPC5BiHAJ/bzGb7+gAC7MfXGxdd0GDihWLecJ4ghOl+zuGY3AfMXgE=

P5UXIDlkQtpBZMJ3WSK7R569PVxKI0y1R3FM+NsVPaPE8JQHTnHgdcfYDT7RH4BkY8VGRbPCERZ9HYqOIezXvkUkyLg/PC93AmpWlh3vCJ55R5CcB76fd1u4fxiQiG8d

function multiply(n: number, ...m: number[]) {
  return m.map((x) => n * x);
}
// 'a' gets value [10, 20, 30, 40]
const a = multiply(10, 1, 2, 3, 4);

6Cs0qPMIls4lyEexk5i2ZZzzPGahZPhMZv95QrNEK1m6VMDkGabGY4CJYiFrn92Bjx2grPewwO4lrljvufytK5UXQ6JErQ3TOb3JL+Xhly3chHoc7prz41umJXn2dY6ZjUsrW8eW2sCGwy5KtFdNPQEwcGqPOBtdHZCninipnaebdUBnp1Z1Y8zmv2zt5S1pGnKabWo1oD4HRo5b23URbid6ci/KjWfLB0zexX+joHdWYKydUc7FEiFSTSVD5MAS7KQIc03nFLcVBmei3cyNYYX2WMPqDDRnFWMOriff1U8XiuVunQ3SGo6TE5Q80P6KaK7qemhsQXlaZUH+ExJLBW6DE5MtvUH70NZlvn6I/4I=

剩余入参

iC5v3YvHrprVMHvnponeFLKCQVW5/1ubikrXWQs2JkJ+RvnDWeaswjUumKdzNjbWFkcFVBGhDhdghz2jdBsb9wG/rA9LsBqM29m+LM4D5disJGq/jxCcAf7NNI6GHpNKS/3JUnteFTnZ33wp6m4EbUQ/9zMYRfD07JVNEMjNkdlRL7aQgXUUtv8hP3YcY9saFGR0OM9+QRatyLB6Th/ycA==

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
arr1.push(...arr2);

y6dNktB/GDtvtZJV4WfY6bHg8qh0FCTFl1O25YKMn14TeL6Pcxj1DsbUKVhhPXrO5pgcM5jfLFpL9HyGfSF+0KhFQUWiRGeiob/5Fh5yvOdTLJvSWtD/PC+4EV5DCCRAhKrw3cnt82x7t5zoXncdCI77sOMbtqWixXI/e10D1fs=

// Inferred type is number[] -- "an array with zero or more numbers",
// not specifically two numbers
const args = [8, 5];
const angle = Math.atan2(...args);

NOARPHFhyZVl6Vr125tWf52Zrys2/MDkRyiIBXOiPpGEspgtR2Oe6iFh5atlj/7A8daJ5R+qVHmGEnufW2vwNAzQxUfbR36wkWws+hoixu394ySoTuEND26UNkl1c4FBlvHhCJqpl2J5IsGRvwz0kUQVKA7hRDL9cV7Hn21O1j0=

// Inferred as 2-length tuple
const args = [8, 5] as const;
// OK
const angle = Math.atan2(...args);

8xeBgdpMZJFfh5tmwZh6No/yUlP28tp4mBsEPvaSN14PqsrnwVCgtaZ6hEK7tXa5/zm6fIST42vvFaGI3UCiCUZErmCbxzvgsKhvaH8WYDSo+M1Y41C8ySYN0wYvKk1z4vIciHZhHs4HsVaGExeAs/jvYHdGMR3qXlFndQrNqdVLQqNoOPmyqEl6Blb3W7H08O86BfpaGa9xEHK3GsIBwQ==

参数解构

CEVL0PqyccLHb9lJ1RcodNaF8hlNM0Htaj82RJxDowl+vifFpcbk8tRrcUPGbGTDflokKpKlNvIct2LSBf6CXQfEw21LFi0YPqzKAY0zj0jP6jQKhY10z29xG6+Nwu0acSrVcxYGtNTtetWTfpUtFuvPey8XST2G5Qxq4mc/evazIycwsGAlpgVZ5LAaHmYmjVSdau0M5lg++izamHmI8Rd47P0sceOWOtjNyffX0d0=

function sum({ a, b, c }) {
  console.log(a + b + c);
}
sum({ a: 10, b: 3, c: 9 });

DFcec1OxqV2DYGwyvawcIlbXruPSKYVYXW/fJSqzO9ZYNqZAVx1NhPw6pxiZgYEi

function sum({ a, b, c }: { a: number; b: number; c: number }) {
  console.log(a + b + c);
}

Xdtxf4vmyXPzFT3Ge2Usl5gp/ZAUWa6W4EmYe0NFrZ6clt4BS0d7m11jsVy078U/8/iV/1Y/RDXst5Y1GOV8jWEV4mTx6xFD2/7xVcSMGpA=

// Same as prior example
type ABC = { a: number; b: number; c: number };
function sum({ a, b, c }: ABC) {
  console.log(a + b + c);
}

函数的可分配性

返回类型 void

CX6Dcgt7afPNHXoAklY94zyN74Eg/GWP5gJ8FFLqwswiPjUFkCwlHA77Gv5fhHrmwj6E88ZzOcPZyGsU/Ut1PKr/JWV+GqDJoeMtODDLJEARwOZD1ue0hthZALfZW2d7

7eqLxp1ywdZlajsfMwRQjZB4MOqCY9jEKX8/jQtYp1Dh3SCIokt+JCl/XzlxvMhtbUiUoZaC9Eg/TmSPXgpiigv42LpEfCfLdxJKgbxrV5TdtKhbnZ8IntV9snu/GvIkwAk9kmVoXu6xI9mkvSeJP3+qquHfGD6fipk8IMWeXv0UZsq6ODvFvMWXQaAo9ucKPaFjwMJ6cAa63a0x0T8gEoG4QNipr1msbkfaTO4nWHdqQMkZlLIoohSy1VGUclGFcvl7S4bipGCjHLVdwKAFEB/9pPgfOtEogGdMjgaQFEpMLvacYEsdLRHzEXb4vbFag8ZYdhZUXw7uPeU0EaUnuwzsX/4qiLqObIjoaXOAfKih3nKMt+ueHVOIDqU+LDId

2Q+ItDO/UhgKCGuD5MAncc0/yikDSAn4mIkzChTgktDe/feQWw1qY/m0cknYUQDnStz9mQs6AuJCMgQMSBN5EvqYdryMz3R2rYwycwrNYwk=

type voidFunc = () => void;

const f1: voidFunc = () => {
  return true;
};

const f2: voidFunc = () => true;

const f3: voidFunc = function () {
  return true;
};

+0CERrchUCb5R+bUaQxZ+YlbQR2OlQxE7pqowxTPPFAFxnblWjf0lH8a76+soFEPDAgnbFB4pqt+DyXUKM3zwFG+1r7KOL+7sia7dycyo2yjRrX/GyVeKOrC3xDvGCy58NTP1rPihoLGCsb+Fm8t4OIuZPeDoi8vJJmbaiOZCTQ=

type voidFunc = () => void;

const f1: voidFunc = () => {
  return true;
};

const f2: voidFunc = () => true;

const f3: voidFunc = function () {
  return true;
};

const v1 = f1();

const v2 = f2();

const v3 = f3();

pFT4x8hRl1zsw1cygLez8fgfFjVz5fPCVSmASBus5X89ascLOFhEdBy2KOz169STWZlyB3UC7ufubdjkKD9EfIe7KRdWqoCbdFLdF3tLRWRcn1x1Gv5F3o12xzrljEbgreLxwA9mXzKVJHpKByniS8R3kJKN7IUTRo823rP03qnPijf2+WbgUdqdmulAXIXm2FZdnn51X+Hk3DY7tosf9wDMxKTnMwg7ZVDJPHCozGgbaoSTVL4jc1T1umJ2TPGKk12WfQgluYsGfXlazLhSi0HgvEuase4hGKs2PsMZUsxe54Ert+KTt3HtSWmZDItz

const src = [1, 2, 3];
const dst = [0];

src.forEach((el) => dst.push(el));

NRhLKV5ezN54NK+A1lDQfRv29TvD5eoAJ9YpRNyO/QFXIZP565dLwXGmWY0sMu2i932J6aXwC52DIqeBdr8iQd7amJ/IF55x3FOEjyjWBy1NNY0G0LfyhfiIpzUpfgyYzXoP3XuPNzFaSHsJ8a9kHVfJwCeU8yRg6aFgBJ3GIqcWQqjcY7C8qzLGTDRP8xGa

function f2(): void {
    return true;
}

const f3 = function (): void {
    return true;
};

8VUXjTddOQiMwsNF9mowAGzpWfI3N7eXsQQSC5rj4rKInPL1+0GSl+LEVEKoqjlgVMALSi8R7cmUOvrX7rKaAp9dfs83t56QopiqsF6MRfU=

    o2iofhuvqZqL3uKBdTBGxx4Yu/rb9RIf8xlWEGAZ0hQgmSvuB3ifZPyBQXtpzUg1fPmrzZKtDPeWim0fZ9rpkUb/KBi8cFk3bq/iJM+jfFTQnhD0WP9R7E2UeisGRkOf5Zn91O/tVP8vK7zhc9gVUZllhbtiBAG35j72ylZirK84PaKPqjwhqt1fMOozsTyiaxkYYwqwAPxdLCjpa57Z5sqcqUGIbhv4IulgObqrKRv9bEQU+3sA4oQV3NrlOQ8j0VLokwgC5fUiK7rzYG3UpMrSRnjeQlrnHIA8rKz1w5tYeo2cRt3RsWQXpk/5uyc3VtbYWMaPZfSJYQur/igOc8on5IFdrEFMHY9BTy/XDuDusY36qnKn2T6w7fEMeuCRkmDmcjZW+hURXpxf5GUu8g==