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
- Host: GitHub
- URL: https://github.com/abelflopes/snippets
- Owner: abelflopes
- Created: 2021-11-10T03:29:25.000Z (over 4 years ago)
- Default Branch: master
- Last Pushed: 2022-03-08T17:34:49.000Z (over 4 years ago)
- Last Synced: 2025-05-11T04:03:09.478Z (about 1 year ago)
- Size: 4.88 KB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
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
*/
});
};
}
```