So I'm new to TypeScript and wanted to know if there's a way to reuse a union type from a 3rd party @types module.
Example, in @types/node we have the following union type for buffer encodings:
// Buffer class
type BufferEncoding = "ascii" | "utf8" | "utf-8" | "utf16le" | "ucs2" | "ucs-2" | "base64" | "latin1" | "binary" | "hex";
And if I have a utility function that passes a value through to Buffer.from() I am required to specify a union type that is compatible with the "BufferEncoding" type, I can't just use "string" like so:
export function convertToBuffer(input: string | Buffer, encoding?: string): Buffer {
if (input instanceof Buffer) return input;
return Buffer.from(input, encoding);
}
Obviously I could just copy and paste the BufferEncoding type from @types/node but this doesn't keep my code DRY, and I am not allowed to import from @types/* modules.
export type BufferEncoding = "ascii" | "utf8" | "utf-8" | "utf16le" | "ucs2" | "ucs-2" | "base64" | "latin1" | "binary" | "hex";
export function convertToBuffer(input: string | Buffer, encoding?: BufferEncoding): Buffer {
if (input instanceof Buffer) return input;
return Buffer.from(input, encoding);
}
I'm not interested in using the "any" type or other methods that loosen the strictness of the type checks. I suspect what I'm asking may not be possible and that's fine.