An open API service indexing awesome lists of open source software.

https://github.com/abelflopes/snippets

Typescript code snippets & utils
https://github.com/abelflopes/snippets

Last synced: 4 months ago
JSON representation

Typescript code snippets & utils

Awesome Lists containing this project

README

          

# Snippets

Typescript code snippets & utils.

## Sequential Promise Array Execution

Unlike `Promise.all`, you can sequentially execute promises using `Array.reduce`.

```ts
const dummyFn = (): Promise =>
new Promise((resolve) => {
console.log("start");
setTimeout(() => {
console.log("end", new Date());
resolve();
}, 1500);
});

const sequentialPromiseAll = (
arr: (() => Promise)[]
): Promise => {
return arr.reduce>(
(prev, curr) => prev.then(() => curr()),
new Promise((resolve) => resolve())
);
};

await sequentialPromiseAll([dummyFn, dummyFn, dummyFn]);
```

[Codepen](https://codepen.io/abelflopes/pen/PoKayWy)

## Create a type with common properties of 2 interfaces

The resulting type will only accept properties `b` & `z`.

```ts
interface I1 {
a: number;
b: number;
z: number;
}

interface I2 {
b: number;
c: number;
z: number;
}

type CommonIntersection = {
[Property in keyof T1 & keyof T2]: (T1 & T2)[Property];
};

const X: CommonIntersection = {
b: 1,
z: 2,
};
```

## Webpack plugin template

```ts
/* eslint-disable @typescript-eslint/no-var-requires */
import { Compiler } from "webpack";
import { log, chalk } from "@advicefront/log";

export type CustomWebpackPluginOptions = {
/* options here */
};

export class CustomWebpackPlugin {
private options: CustomWebpackPluginOptions;

constructor(options: CustomWebpackPluginOptions) {
this.options = options;
}

/**
* Apply function (called by webpack)
* Webpack compiler docs: https://webpack-v3.jsx.app/api/compiler/
* @param compiler Compiler
*/

public apply = (compiler: Compiler): void => {
// Display all hooks
Object.keys(compiler.hooks).forEach((hook) => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
compiler.hooks[hook].tap("CustomWebpackPlugin", () => {
log(chalk.yellow(hook));
});
});

compiler.hooks.beforeCompile.tapPromise("CustomWebpackPlugin", async (): Promise => {
/**
* Code to execute here
*/
});
};
}
```