Created
January 8, 2021 11:51
-
-
Save karol-majewski/71467b671983046bc40ae9bf674dcbcd to your computer and use it in GitHub Desktop.
Promisify callback APIs using TypeScript leading rest elements in tuples (https://github.com/microsoft/TypeScript/pull/41544)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as fs from 'fs'; | |
const promisify = <T>(fn: Promisifiable<T>) => (...args: DropLast<Parameters<typeof fn>>) => | |
new Promise<T>((resolve, reject) => { | |
fn(...args, (err: Error | null, val: T) => (err ? reject(err) : resolve(val))); | |
}); | |
async () => { | |
try { | |
const pkg: Buffer = await promisify(fs.readFile)('package.json'); | |
} catch {} | |
}; | |
type DropLast<T extends TupleLike> = T extends readonly [...infer U, any] ? U : [...T]; | |
type Callback<T> = (error: Error | null, value: T) => void; | |
type Promisifiable<T> = { | |
bivarianceHack(...args: [...unknown[], Callback<T>]): void; | |
}['bivarianceHack']; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment