我正在创建一个输出图像的函数。它需要接受format、exportType和pathOrWithMetadata参数。我有以下代码:
interface ExportMetadata {
data: Buffer;
width: number;
height: number;
}
export type Format = "png" | "jpeg";
export type ExportTypes = "file" | "buffer";
export type Output<ExportType> = ExportType extends "file" ? undefined : Buffer;
export default async function exportTo<ExportType extends ExportTypes>(
image: Image,
format: Format,
exportType: ExportType,
pathOrWithMetadata?: string | boolean
): Promise<Output<ExportType>> { ... }这将确保如果exportType是"file",则将返回undefined。但是,如果exportType是"Buffer",则将返回Buffer。现在,我需要Buffer返回类型依赖于pathOrWithMetadata参数。首先,如果exportType是"file",则pathOrWithMetadata必须是字符串。如果exportType是"buffer",那么它需要是布尔值。如果布尔值为true,则返回类型需要为ExportMetadata。如果是false 或 Buffer,则需要返回Buffer。
以下是我尝试过的:
interface ExportMetadata {
data: Buffer;
width: number;
height: number;
}
export type Format = "png" | "jpeg";
export type ExportTypes = "file" | "buffer";
export type PathOrWithMetadataOptions = string | boolean;
export type Output<ExportType, PathOrWithMetadata> = ExportType extends "file" ? undefined : (PathOrWithMetadata extends true ? ExportMetadata : Buffer);
export default async function exportTo<ExportType extends ExportTypes, PathOrWithMetadata extends PathOrWithMetadataOptions>(
image: Image,
format: Format,
exportType: ExportType,
pathOrWithMetadata?: PathOrWithMetadata
): Promise<Output<ExportType, PathOrWithMetadata>> { ... }这适用于以下用例:
exportTo(image, "png", "file", "example.png"); // Promise<undefined>
exportTo(image, "png", "buffer", true); // Promise<ExportMetadata>
exportTo(image, "png", "buffer", false); // Promise<Buffer>但是当pathOrWithMetadata是undefined的时候就不起作用了
exportTo(image, "png", "buffer");这里的返回类型是Promise<ExportMetadata | Buffer>。如何使返回类型为Promise<Buffer>?
发布于 2020-10-15 21:56:41
我发现解决方案是为PathOrWithMetadata设置一个默认值,如下所示:
export default async function exportTo<ExportType extends ExportTypes, PathOrWithMetadata extends PathOrWithMetadataOptions = false>(...): Promise<Output<ExportType, PathOrWithMetadata>> { ... }https://stackoverflow.com/questions/64379064
复制相似问题