输入选项的基本返回类型

时间:2019-02-03 20:11:00

标签: typescript

File可以将content设置为string或设置为Buffer,具体取决于是否设置了编码选项。

我试图重载此功能,以便能够根据输入确定结果。

async function readFromFileQuery (fq: Merge<FileQuery, { encoding: FileEncodings }>): Promise<Merge<File, { content: string }>>;
async function readFromFileQuery (fq: Merge<FileQuery, { encoding: null }>): Promise<Merge<File, { content: Buffer }>>;
async function readFromFileQuery (fq: FileQuery): Promise<File> {
    const { path, encoding, flag } = FileQueryHandler.make(fq);
    const content = await promisify(fs.readFile)(path, { encoding, flag })
    return { path, encoding, flag, content };
}

readFromFileQuery({ path: './File.ts', encoding: FileEncodings.UTF8 }).then(r => {
    console.log(r);
});

如何在TypeScript中实现这一目标?

1 个答案:

答案 0 :(得分:0)

不确定所有类型是什么,但是如果参数类型的形状在重载之间不兼容,则很容易在参数上重载。

这按预期工作

import { promisify } from "util";
import * as fs from 'fs'


async function readFromFileQuery(fq: Merge<FileQuery, { encoding: FileEncodings }>): Promise<Merge<File, { content: string }>>;
async function readFromFileQuery (fq: Merge<FileQuery, { encoding?: null | undefined}>): Promise<Merge<File, { content: Buffer }>>;
async function readFromFileQuery (fq: FileQuery): Promise<File> {
    const { path, encoding, flag } = FileQueryHandler.make(fq);
    const content = await promisify(fs.readFile)(path, { encoding, flag })
    return { path, encoding: encoding as FileEncodings, flag, content };
}

readFromFileQuery({ path: './File.ts', encoding: FileEncodings.UTF8 }).then(r => {
    console.log(r.content); // string
});

readFromFileQuery({ path: './File.ts' }).then(r => {
  console.log(r.content); // Buffer
});

readFromFileQuery({ path: './File.ts', encoding: null }).then(r => {
  console.log(r.content); // Buffer
});

// Some assumptions
type Merge<T, U> = Pick<T, Exclude<keyof T, keyof U>> & U 
enum FileEncodings {
  UTF8  ="UTF8"
}
interface FileQuery {
  path: string,  flag?: string, encoding?: FileEncodings | null
}
export interface File {
  path: string,  flag?: string, encoding: string, content: Buffer | string
}

declare var FileQueryHandler: {
  make(fq: FileQuery) : FileQuery
}