TypeScript 入门教程

发布于 2024-04-02 00:22:17 字数 5079 浏览 28 评论 0

简介

  • TypeScript 为 JavaScript 添加了静态类型定义。
  • TypeScript 是 JavaScript 的超集。
  • TypeScript 优势在于类型推断。
  • Typescript 通过 babel 或者 TypeScript compiler(tsc) 转译代码。

第一个例子

hello.js

function greet(person: string, date: Date) {
    console.log(`Hello ${person}, today is ${date.toDateString()}!`);
}
greet("Maddison", new Date());

tsc hello.ts
function greet(person, date) {
    console.log("Hello " + person + ", today is " + date.toDateString() + "!");
}
greet("Maddison", new Date());


tsc --target es2015 hello.ts
function greet(person, date) {
    console.log("Hello " + person + ", today is " + date.toDateString() + "!");
}
greet("Maddison", new Date());

注意,转译后,参数类型会被擦除。 (person: string, date: Date) => (person, date)

严格模式

  • noImplicitAny 拒绝 Any 类型
  • strictNullChecks 严格 Null 值检测

类型声明

接口声明

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);

定义方法

function getAdminUser(): User {
  //...
}

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

组合类型

function getLength(obj: string | string[]) {
  return obj.length;
}
TypePredicate
stringtypeof s === "string"
numbertypeof n === "number"
booleantypeof b === "boolean"
undefinedtypeof undefined === "undefined"
functiontypeof f === "function"
arrayArray.isArray(a)

泛型

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
const object = backpack.get();

结构类型系统

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

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

// prints "12, 26"
const point = { x: 12, y: 26 };// point is not Point type
printPoint(point);

JS 类型与 TS 类型

JS 类型描述对应 TS 类型
Numbera double-precision IEEE 754 floating point.number
Stringan immutable UTF-16 string.string
BigIntintegers in the arbitrary precision format.bigint
Booleantrue and false.boolean
Symbola unique value usually used as a key.symbol
Nullequivalent to the unit type.null
Undefinedalso equivalent to the unit type.undefined
Objectsimilar to records.object

Other important TypeScript types

TypeExplanation
unknownthe top type.
neverthe bottom type.
objectliteral eg { property: Type }
voida subtype of undefined intended for use as a return type.
T[]mutable arrays, also written Array<T>
[T, T]tuples, which are fixed-length but mutable
(t: T) => Ufunctions

Unit types

例如,字符串 foo 的类型为 foo

declare function pad(s: string, n: number, direction: "left" | "right"): string;
pad("hi", 10, "left");//ok

let s = "right"; // s is widen to string type!
pad("hi", 10, s); // error: 'string' is not assignable to '"left" | "right"'

let s: "left" | "right" = "right";// shorten s type range
pad("hi", 10, s);//ok

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

关于作者

却一份温柔

暂无简介

文章
评论
27 人气
更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文