I have been experimenting with the coding TypeScript playground and here's what I've come up with so far:
export type Encoding = 'buffer' | 'blob' | 'base64'
export default async function md2docx<E extends Encoding>(
text: string,
encoding: E,
): Promise<
E extends 'blob' ? Blob : E extends 'buffer' ? number : string
> {
switch (encoding) {
case 'buffer': return 10 //Buffer.from(text)
case 'blob': return new Blob([text])
case 'base64': atob(text)
}
}
md2docx('foo', 'blob').then(output => {
output.arrayBuffer
})
I am aiming to specify the encoding type for the function md2docx
and ensure the correct type is returned, while also having proper typing in the output
variable. Currently, my code is not functioning as intended. If I go with the current setup, I have to manually check if output instanceof Blob
, which is something I would prefer to avoid:
export type Encoding = 'buffer' | 'blob' | 'base64'
export default async function md2docx<E extends Encoding>(
text: string,
encoding: E,
) {
switch (encoding) {
case 'buffer': return 10 //Buffer.from(text)
case 'blob': return new Blob([text])
case 'base64': atob(text)
}
}
md2docx('foo', 'blob').then(output => {
if (output instanceof Blob) {
output.arrayBuffer; // .arrayBuffer property exists.
}
})