React 18 进入 Beta 阶段、TypeScript 4.5 发布 | 淘系前端架构周刊 211122 期

699

🗞 News

React 18 进入 Beta 阶段

本月 16 日,React 官方发布 Twitter 宣布 React 18 由 Alpha 阶段进入 Beta 阶段:

原文链接:Thanks to the incredible efforts of the React 18 Working Group, we're upgrading the stability of the React 18 release from Alpha to Beta!

Electron 16.0.0 发布

Release Blog:Electron 16.0.0 | Electron

TypeScript 4.5 发布

本次更新的几个重要内容包括:

  1. 字符串模板类型可以作为类型判别式,用于类型推导
export interface Success {
  type: `${string}Success`;
  body: string;
}

export interface Error {
  type: `${string}Error`;
  message: string;
}

export function handler(r: Success | Error) {
  if (r.type === 'HttpSuccess') {
    // r 会被推导为 Success 类型
    let token = r.body;
  }
}
  1. 新的 module 配置 es2022,允许在 TypeScript 中使用 es2022 语法(top-level await
  2. 在使用条件类型时消除尾递归
  3. 允许在导入类型时使用新的类型导入修饰符
import type { BaseType } from './some-module.js';
import { someFunc } from './some-module.js';

export class Thing implements BaseType {
  // ...
}

现在可以改写为:

import { someFunc, type BaseType } from "./some-module.js";

export class Thing implements BaseType {
  // ...
}
  1. &etc.

Release Blog:Announcing TypeScript 4.5 - TypeScript

📦 Open Source

Zod

适用于 TypeScript 的静态类型校验库,适用于在框架层辅助建立全链路的类型安全,如一体化框架 BlitzJS。同时,社区已经有直接从 TS 代码转换到 Zod Schema 的库。

GitHub Repo:colinhacks/zod: TypeScript-first schema validation with static type inference

tsd

命令式的 TypeScript 类型定义校验,适用于对工具类型进行单元测试。

GitHub Repo:SamVerschueren/tsd: Check TypeScript type definitions

Vitedge

基于 Vite 的 ESR 支持。

GitHub Repo:frandiox/vitedge: Edge-side rendering and fullstack Vite framework

📑 Article

TypeScript 之 More on Functions

原文链接:TypeScript 之 More on Functions

TypeScript 之 Narrowing

文章通过 case by case 的方式讲解了 TypeScript 中的各种类型收窄,其中一段关于类型判断式的代码示例非常值得学习!

function isFish(pet: Fish | Bird): pet is Fish {
  return (pet as Fish).swim !== undefined;
}

通过类型判断式的方式,能够有效解决 TypeScript 类型推导错误的问题,在编码阶段即可发现代码问题。

例如:

interface Fish {
  swim: () => void;
}

interface Bird {
  fly: () => void;
}

function isFish(pet: Fish | Bird): pet is Fish {
  return Boolean((pet as Fish).swim);
}

function petFuncCall(pet: Fish | Bird) {
  if (isFish(pet)) {
    // pet: Fish
    pet.swim();
  } else {
    // pet: Bird
    pet.fly();
  }
}

如果 isFish 方法的返回值定义不为 pet is Fish,而是 boolean,则 TypeScript 就无法做出正确的类型推导:

Playground:TypeScript Playground

原文链接:TypeScript 系列之 Narrowing - 知乎

Svelte 实现原理

文章从 Svelte 的编译产物入手,详细介绍了 Svelte 的工作原理,清晰易懂。

原文链接:简单好懂的 Svelte 实现原理