About TypeScript

Useful TypeScript features:

  • infer
  • never
  • keyof + in


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

Here’s an example:

1const User = {
2  id: 123,
3  username: 'John',
4  email: '[email protected]',
5  addons: [
6    { name: 'WriteAddon', id: 1 },
7    { name: 'TodoAddon', id: 2 }
8  ]
12type UnpackArray<T> = T extends (infer R)[] ? R: T;
14type AddonType = UnpackArray<typeof User.addons>; // { name: string, id: number }


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

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

Triple-Slash Directives

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

1/// <reference path="/node_modules/webpack/types.d.ts"/>

像这样使用三斜线指令之后,new webpack.DefinePlugin({}) 就有类型提示了。

/// <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.

Why are functions returning non-void assignable to function returning void?


void function 可以 declare return any 不会报错
但是实际上使用返回值时 返回值的类型是 void 约等于 undefined 场景类似于
const arr : number[] = [];
const arr2 : Array<number> = [1,2,3];
arr2.forEach(item => arr.push(item));
void function 重要的是 返回值忽略 即不使用返回值