TypeScript 相关

Useful TypeScript features:

  • infer
  • never
  • keyof + in

infer

The infer keyword allows you to deduce a type from another type within a conditional type.

Here’s an example:

typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
const User = {
  id: 123,
  username: 'John',
  email: 'john@gmail.com',
  addons: [
    { name: 'WriteAddon', id: 1 },
    { name: 'TodoAddon', id: 2 }
  ]
};


type UnpackArray<T> = T extends (infer R)[] ? R: T;

type AddonType = UnpackArray<typeof User.addons>; // { name: string, id: number }

never

The never type represents a value that is never observed.

In a return type, this means that the function throws an exception or terminates the execution of the program.

keyof + in

typescript
1
2
3
type DeepReadonly<T> = {
  readonly [P in keyof T]: DeepReadonly<T[P]>;
};

Triple-Slash Directives

最近遇到的一个问题,pnpm install 之后 @types/node, @types/jest 等都没有提示了,找了挺久似乎都没有思路,最后偶然尝试在 d.ts 文件里加上 /// <reference types="..." /> 就好了

/// <reference types="..." />

Similar to a /// <reference path="..." /> directive, which serves as a declaration of dependency, a /// <reference types="..." /> directive declares a dependency on a package.

The process of resolving these package names is similar to the process of resolving module names in an import statement. An easy way to think of triple-slash-reference-types directives are as an import for declaration packages.

For example, including /// <reference types="node" /> in a declaration file declares that this file uses names declared in @types/node/index.d.ts; and thus, this package needs to be included in the compilation along with the declaration file.

Use these directives only when you’re authoring a d.ts file by hand.

For declaration files generated during compilation, the compiler will automatically add /// <reference types="..." /> for you; A /// <reference types="..." /> in a generated declaration file is added if and only if the resulting file uses any declarations from the referenced package.

For declaring a dependency on an @types package in a .ts file, use types on the command line or in your tsconfig.json instead. See using @types, typeRoots and types in tsconfig.json files for more details.