Skip to content

Repository files navigation

learn-typescript

TypeScript 是一种由微软开发的自由和开源的编程语言。它是 JavaScript 的一个超集,而且本质上向这个语言添加了可选的静态类型和基于类的面向对象编程。

简而言之,TypeScript 是 JavaScript 的超集,具有可选的类型并可以编译为纯 JavaScript。从技术上讲 TypeScript 就是具有静态类型的 JavaScript。

  1. 了解基本数据类型
  2. 全面了解 tsconfig
  3. 最佳实践
  • 基本类型:string、number、boolean、symbol、bigint、null、undefined
  • 引用类型:array、Tuple(元组)、object(包含 Object 和{})、function
  • 特殊类型:any、unknow、void、nerver、Enum(枚举)
  • 其他类型:类型推理、字面量类型、交叉类型

对比

  1. any vs unknown
  2. interface vs type

注意在键值语法中 KeyType 类型只能是 string、number、symbol 或则模板字面量,不能是纯字面量

unknown 与 any 的最大区别是

  • any: 任何类型的值可以赋值给 any,同时 any 类型的值也可以赋值给任何类型。
  • unknown: 任何类型的值都可以赋值给它,但它只能赋值给 unknown 和 any
// 什么时候推荐用 type 什么时候用 interface?

// 推荐任何时候都是用 type,type 使用起来更像一个变量,与 interface 相比,type 的特点如下:

// 表达功能更强大,不局限于 object/class/function
// 要扩展已有 type 需要创建新 type,不可以重名
// 支持更复杂的类型操作

// 基本上所有用 interface 表达的类型都有其等价的 type 表达。
// 在实践的过程中,我们也发现了一种类型只能用 interface 表达,无法用 type 表达,那就是往函数上挂载属性。

interface FuncWithAttachment {
  (param: string): boolean;
  someProperty: number;
}

const testFunc: FuncWithAttachment = {};
const result = testFunc('mike'); // 有类型提醒
testFunc.someProperty = 3; // 有类型提醒

配置说明

  • TypeScript 严格模式 "strict": true
  • 禁止隐式 any noImplicitAny: true
  • 严格的空检查 strictNullChecks: true
  • TypeScript 中的类型收窄
    • 变量可以从不太精确的类型转移到更精确的类型,这个过程称为类型收窄。

定义接口数据

// 在 Pro 推荐在 src/services/API.d.ts 中定义接口数据的类型,以用户基本信息为例:

declare namespace API {
  // 用户基本信息
  export type CurrentUser = {
    avatar?: string;
    name?: string;
    title?: string;
    group?: string;
    signature?: string;
    tags?: {
      key: string;
      label: string;
    }[];
    userid?: string;
    access?: 'user' | 'guest' | 'admin';
    unreadCount?: number;
  };
}

// 推荐 json2ts 等网站来自动转化。

// 在使用时我们就可以很简单的来使用,d.ts 结尾的文件会被 TypeScript 默认导入到全局,
// 但是其中不能使用 import 语法,如果需要引用需要使用三斜杠。
export async function query() {
  return request<API.CurrentUser[]>('/api/users');
}

// props
export type UserProps = {
  userInfo: API.CurrentUser;
};

参考文档

其他文档

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages