面向 JavaScript 程序员的 TypeScript

TypeScript 与 JavaScript 有着不同寻常的关系。TypeScript 提供了 JavaScript 的所有功能,以及在这些功能之上的附加层:TypeScript 的类型系统。

例如,JavaScript 提供像 stringnumber 这样的语言原语,但它不会检查你是否一致地分配了这些。TypeScript 可以。

这意味着您现有的工作 JavaScript 代码也是 TypeScript 代码。TypeScript 的主要好处是它可以突出显示代码中的意外行为,从而降低出现错误的可能性。

本教程简要概述了 TypeScript,重点介绍了它的类型系统。

推理类型

TypeScript 了解 JavaScript 语言,并会在许多情况下为您生成类型。例如,在创建变量并将其分配给特定值时,TypeScript 将使用该值作为其类型。

let helloWorld = "Hello World";

J9HOakI45U2eLaKzLN/Dq91Z05JUPe2M84Mm4WBZBiRZ2lc56XB3rMufXTNQB8cquQDIX7hRF9umGj9LZlwxc5Upd5yxH/jVGc1FrLayQzxta6vGdqBc1JyrbgAo2j5wC1GZ4k7DsYJ/p52mUAGRv/J3YjZEb0ge8G37fbGFQRtNW0XEBYu5EtQONc3IcyUGgjU9lbMJeNm23Hh6ynp1VkcNDDT99LAq/4C2iUxZ2HUrzuAg/JBO8L3B5QE30xQdAsKoOVzax3vwIc9bHMcTwyek52+yj+n4fWk6lV46jm3dQH/ptM6KmzOzR4EXoav04KpWPY1FNbt4T6qbecSo/bwnKVOH/JSjZgLOK+K/+2+2o1YvgKhUztrdMyV6GBFhpsVi+44zP8Pavm15K/3eZEjjkcG9t0LMckVYfI0fcmFKXw4z+vEI3HvU1j8Z6O4I

O//37QSPpgWEIzeprnglUevPsQXrABBn9kvagOfTqa0dStpPxRMjDaUf41gAF+6qNAQKgy7U2qGOvUNOAg6eF3a/W9HQT2rv3WQnLaG1/3/Ak15N4Choy8iBGixS6a6S21mYQYoae/j5tC5YeJqglboPV3EWluPU5vAfG94SkytIhN0pU0gMiryGoTQYuGpfDC23ncLJ59GujNB0aaCMMkHHBNsodwWFv/2talWnGIq9CiPCXSYVS5VzQlzsFSm/

定义类型

Rx6jhc2syiKcjzjEh4VflOIYonjjVvMLTMTXBZP8pIZOFE3jp1eEXT+hZEK0eZ3ma3GCTKIe6tC/6TqUUlIx0Llml9LHzmpc7Sc4PcX2LGtSgOiQfBRzgb84Tadelv1GQ9xiFO+b4HRcRANdcAuKDEeqyB1wUnp2Delmo/+LVugCH2jVv+Uhc8bKhTagcSqmj2+06TFiSyHlZOcUfLNvxN2hO+6STNknaqPv2O1ZJBaB9hSfTcphnIKS3tyMGTY+T1J1n1X+uEgqhuE0bGkCMop07MVpfusTxq9zHncOlmR7UMQ+k3SchW4xkkUy5f7UbIpNkzTYHrFJ7IECCZf5VA0PG69U0EqxfTyk2uN6E6Z8TPDeBjkgxtwtlzxgek4G6eLk14FpmKD4Dk862VrKiIHxbJ9l9SSbeZl604WI5u4=

XGwTk/czAAA1rbgro3T9Sd+FUZVa7avS6tiZLRjVqRFR86XuDVUJmnaA3QjEPZktfxfeTTxvTPSMAlYYwNrir8io9PSdaH04F1AHthOeLtjDJH/nEQxYnN9b0fNSQ7lvu5kM0nbp498sulRUclIW8pRqSJN5C9lpTz5u07vclCxyvGP6NvHntxoeVbEEOc2w

const user = {
  name: "Hayes",
  id: 0,
};

nPV7VKpiArkSLfsPV18bokKjeXJBTSwzfj4Ijnxbqvb7H2cVBdBmn1xNx8vukdWBT7mNYBg9UJ7snyG2CMPmZAFr+MXfijrsKnC6rQkkUkA=

interface User {
  name: string;
  id: number;
}

DPdE+oDmzWuhn1b5rxrm5siVsKZRtnmJGSNBG79InVUf/usqoY+zgVBYkxgoLn6CCHX7nKJogUwkHI1b79qFCGeDTDQVRuv9W101kqY4EXoLiB65xmH44Kwhb4UOT+MSoYAGcFxqJZ7msO5WjmGiLsEjsrSHQGdGy0XED+BoxZ+pnTJtYvjScDfMFl6g5ng3rrvge2nXkswkuTr4RlobLQ==

interface User {
  name: string;
  id: number;
}
const user: User = {
  name: "Hayes",
  id: 0,
};

IzrSm3CLgM7to8Ocy3cJnhXOGApDFt1THgU2Tiw/wcMU1VcWAWg403CQU6sOjGLJzt38BXK8PGj4PF7Q9ZSZS/09AITrsMAcRGR+bI8lKIvT9ssWgwPZoFpGv1eNTFin

interface User {
  name: string;
  id: number;
}

const user: User = {
  username: "Hayes",
  id: 0,
};

aJkJXq4K9Zz2xjp+Y6GY/d5ItFjFKLUdsYZ5pXjZUf1G10v9U9lzif73AH7oHJQntaM3tstehzXVe1xWKn+HdTg2x2DhpRFKn7wxZn6RQroam593IAN8sAt/uvpGXX1XRg2EOc/ChUQJ7Fpw5VIeFOIPzi3uIngoufMBNEnV3XE=

interface User {
  name: string;
  id: number;
}

class UserAccount {
  name: string;
  id: number;

  constructor(name: string, id: number) {
    this.name = name;
    this.id = id;
  }
}

const user: User = new UserAccount("Murphy", 1);

rPgTdUi185sFY3uTPamtUgLIXnGqnWDS7bpu5KnmTE0gwaGbQHTJF16hRyYsmzqDVLEI/HET3IFGN2DBVPUjhQ==

interface User {
  name: string;
  id: number;
}
function getAdminUser(): User {
  //...
}

function deleteUser(user: User) {
  // ...
}

QQ9Y4X9XLo9CgBuxUrdXJMRSnct6r4cavxPVOne141uUdckq/Bj+QUsIeA8EYKkFksHc5UG2KQHiaV5z3O1yKnAZpPHFLBwYTv7foH8/ycDKnPnfk3WQ+Ch5WcF3e3YviZNCMxkg6gfP8ywv1BQ5iLHqDKF/w8l247HF1vJIzeveQcSJjd+X9W4yjrawLNHb+eWT8Z8zRh8nj17l80sm73gGQDFmQXPC3f/AehG4+8uNZiGyFJuqWaoY7So/6MQut8DsJ4KU/q1bQZwHFRujvFhLfVckZH86xBg08AGl9v+KTV9UyroPv2hkwhkSDfaLBf8mloh5lNKCSahDvdRjXl17qh7Nds+YvmWGoU+nXNXhtIQq6OgbG0AXGdzz/ziAauvV1u/oMIYt8KtPJtoTcE2TBxzvgb+O9BYcZJ7osguhIofhCkQb1vyVDgB06zG+dKlCMv9M0/K248bghdumrJ4ddHPP+T+Qtl01BOyj8/DnG+5fSNkP5+K0xno6VFu3l0rxCRYDacVDNmVQgQix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C2Tn+srM70tKEWkaJBJCIzDh8fpc0ZL3JiZT5dUuDbquFfzT92Zl+dmg=

type MyBool = true | false;

sixYikYlYenT2nPDGTk/b9HTmeux+p6dMwc4cOKosgz5wbrua4S2SwodaHmf6yth+G6nTjLgaRUNMUyMKCsTbFMSSGUCD+T0Xfdb3jINCJCf3i8PHTa5jJtI9ori6v3Ng38KEHoxxpdiAbYwf/3ZNLGBCI/iw+y85cy0fFIrel7RVxADIdYktIV/yb6F9j1wlN3TshqZlDNK5K/uyzKvTsDD+ZGWDemoxrGnsS3rrqR60b1SRKZbbpguLdV/Ky3z

vjIV0Zf1+ZHW4UGABlmrDqG1/QvzxHlCrt7dsASXcoFl1MtsS1eqcAVlhg8XGfJ0yU5HGkyX88K97/2r4A5KRggO0qBy5wBhbGVvA/1tChmL7XIuH97H7pFFJNPhM4Us9Wi0z6b/N+04/T8Yqx6vYKnIORaYhulYgBIpskzWehQumu1gkD0kRXQGWRvHVmPtetDh+lcX120WiG97hk6vXsZkqucEr1Z8dS6Cq6UdpOA=

type WindowStates = "open" | "closed" | "minimized";
type LockStates = "locked" | "unlocked";
type PositiveOddNumbersUnderTen = 1 | 3 | 5 | 7 | 9;

y/SooofsQ4yCuezkKR3S1UAP8v/tavUl62XgjkRtlQLTZzO6NPoj8kkC6Fn2KBtHVhwRMW8IAFrn1tS6/wfoytG5TVW9VD5cZu7wHE298AH9qoHVvfWloPrapGU+e/gHqxDYee+n8JhTYRErw6dyvuZ5VhK7D+DcBSZSMnLC/ZQe5AjY46VOp+8fRFYB7VdW

function getLength(obj: string | string[]) {
  return obj.length;
}

bL+vP1J5O8n/v9/UpsKuv7oWdo6XaYE1hGeCLWHAyvb+QfznW4SARjGOF0BB4gbKgC98x7DYxF3aD47YYztsZA==

类型谓词
字符串typeof s === "string"
数字typeof n === "number"
布尔值typeof b === "boolean"
未定义typeof undefined === "undefined"
函数typeof f === "function"
数组Array.isArray(a)

W8vuIvHUuFFYc561jQO0W7bJW1R1O8tv6nKMMWmi4KuB71kwpXTdV5SgJLsZtQbKuoHF9RL8ZB9xnzpCWP9ThgQtsvS+YLdFnMIP3FARiulo3ZmjXmKRCMGqdQsIEN2S7nBC5LUD2cTnusq+RjZI7w==

function wrapInArray(obj: string | string[]) {
  if (typeof obj === "string") {
    return [obj];
  }
  return obj;
}

泛型

uocadyRwMQC1ahVYjdjIKTH+k9j+mDj2ewjkd5/obSVP2vfPED6nTQbzUzkxHixQ1ZPUV8bnrl/frt5UvXFIsHh0LIAv3m1Z5GXhv3GHt86vKNQRUzCz1u7/o9qnrfSdfAwF6X4tS12zpHbGLJt5WkmZmdXpOtoZfPYzb48mKMXgmYh83fGe1hzMp1smP3IDi+DiTKPquqEl+SAkdn8UV9iLK4HoC+aVncV9QfyAyCo=

type StringArray = Array<string>;
type NumberArray = Array<number>;
type ObjectWithNameArray = Array<{ name: string }>;

qi4Kpn54G39E2R3Hkpn4YVBWPKQC+8Jfp6//nPAGZfBn8dltPi5cJfHJfnusGhTbqQnt8Gd79szRhppXvj8hOg==

interface Backpack<Type> {
  add: (obj: Type) => void;
  get: () => Type;
}

// This line is a shortcut to tell TypeScript there is a
// constant called `backpack`, and to not worry about where it came from.
declare const backpack: Backpack<string>;

// object is a string, because we declared it above as the variable part of Backpack.
const object = backpack.get();

// Since the backpack variable is a string, you can't pass a number to the add function.
backpack.add(23);

结构类型系统

1nonMNogeVQPUHpRWfouqfr+WDYZ9D9174NoiPm4aAwHMDV3V1zFEorqRzuzxJ9hnlSpchJJ0Qc84RBlEP2obcwzPANsZfo2SxjoZ+axCOhcjxesxZmn0N58j3fOGP9XixmIsVRlApyhWKzY4LdeIQXOe5p9gbgdxiL9hVhsQRI=

KCwKa2DAqB0TnvTRf2iD9bEj+2p5ly3ZV942s9ErQf/vbBBE0p4LT35YlsI9Dk3CLIutne0cAkhpDV3aQhfmuad0VjKjkd07ScDqYuy6U+VKsxR1N4WubcOqeQAfxz9RUdsRWa9pfFtgzTiQdGh0Xw==

interface Point {
  x: number;
  y: number;
}

function logPoint(p: Point) {
  console.log(`${p.x}, ${p.y}`);
}

// logs "12, 26"
const point = { x: 12, y: 26 };
logPoint(point);

0/mghNIUAsY4pU5eQAQxkbFaM9GwkzJZTBq4YqNLb1esi0jnXKoFNaup1he7CP59BNZ5dPsG1u7lVtg9WBeZj3SsnKELREaL+zg/meKNuWoLRJ+fHBR96u0+X6JoMGszgrdgUapApaqrCo+XsTJ6J2vJCpi1K8k0JynSQJ2k1H8dtV8AFyg/dP9+9L+L7/NlehFQO7li3wz8uf2sRpXDKqnbn/8qmZcKJH93rHNCBzHvd9+Zcr93fjuHZSFVN3KPN4aetQe5N3RJTKCRdu6J/pb2yh0nHqNiymjIx3pJaw00O3LwnfRSX7fWWSYsOtM6

f94K0657TRftcn6NKr8IxBZAPGNcAJk7oJiDmvFYcK3kZnS63Jrd526O08h3Q9YtqKTmoNtMUPRMb4h6gs2LAg==

interface Point {
  x: number;
  y: number;
}

function logPoint(p: Point) {
  console.log(`${p.x}, ${p.y}`);
}
const point3 = { x: 12, y: 26, z: 89 };
logPoint(point3); // logs "12, 26"

const rect = { x: 33, y: 3, width: 30, height: 80 };
logPoint(rect); // logs "33, 3"

const color = { hex: "#187ABF" };
logPoint(color);

TE3RIO/NrBwmeJ1xhBMOcy3DkNac5aWnGY/E35dTdhJlcanuL+pSU+dVnCpJhx+wtk4VQoH6dYlEiihX5sLVEA==

interface Point {
  x: number;
  y: number;
}

function logPoint(p: Point) {
  console.log(`${p.x}, ${p.y}`);
}
class VirtualPoint {
  x: number;
  y: number;

  constructor(x: number, y: number) {
    this.x = x;
    this.y = y;
  }
}

const newVPoint = new VirtualPoint(13, 56);
logPoint(newVPoint); // logs "13, 56"

Wgh6qXkF5eLyVWO28Ywj28nD4PQV6Lwtm5lubStC1cAVOKwYi7YJXLTF47JMlcUVj7baEZqS3XUYRnMureVw6obVMRkwvRvz8IrKz73qzbJi/kN/pYxJt5PBT1YWF277RJXyDXvNywE92it/cVKiVQ==

下一步

oJUd3pBUdx7HvqJDBg7bnGQKP1I0P2oS8GTtIuRkgnk6ef08Js5uUlPynMFrYI1W1Vw0qFaPNNI08qmzyV+ol0eoS/eJafNTeK+XEgneYs7QEPRdvMcFq6Zec4AWk9RMi8pvwh+O0YCUP6qFMcZqgA==

    XqENqNXmbWbgsXT4GKmiUzgNlXiO6oIhKqog7Ys3CpIbo/qmjy3U0jSSZQXMlQHid+GQPYNjemdsHUyxFqXeiNo/q774zL/RCOcD96urzQyIOHngNVfroAGZX6yYXda9zP2EkL+FYd29Bpo/K6gMX2y051A0vLBZNO+uFY+pfCBJIfpxhzNi7/BdxILWSLmoEfR1DczvKa07qdopAU7+hwI6F3oPJtRfivXg7eqDT/gB23NFCpTz1uHuai5Vp/A2