OOP的一般租户是派生类应该能够替换基类。在这种情况下,派生类不能替换基类,因为派生类具有返回类型(
null
)基类的客户机不知道会发生什么。
那个啤酒说我们可以接近你想要的。
首先,我不使用只包含静态方法的类,而是创建一个包含实例方法的类,并声明
const
的实例类型,并将其导出以供人们用作单例。
readFileFromFileQuery
方法是抽象的,类是泛型的。这允许我们插入一个返回
File
File | null
不违反Typescript(和OOP)一致性规则
最终的解决方案是这样的(我填写了一些类型,不确定它们的实际定义是什么,但我添加了代码无错误所需的最低限度的内容):
abstract class _FileHandlerBase<T> {
abstract readFileFromFileQuery(fq: FileQuery): Promise<T>;
async readFile(a: Path | FileQuery, b?: Omit<FileQuery, 'path'>): Promise<T> {
if (typeof a === 'string') a = FileQueryHandler.getFromPath(a, b);
return this.readFileFromFileQuery(a);
}
async readFiles(a: (Path | FileQuery)[] | Directory, b?: Omit<FileQuery, 'path'>): Promise<T[]> {
if (a instanceof Array) return Promise.all(a.map(p => this.readFile(p, b)));
return this.readFiles(PathHandler.getFromDirectory(a), b);
}
async readFilesFromDirectory(a: Path | FileQuery, b?: Omit<FileQuery, 'path'>): Promise<T[]> {
const ps = await DirectoryHandler.readDirectory(a);
if (typeof a === 'string') return await (this).readFiles(ps, b);
return await this.readFiles(ps, a);
}
}
export class _FileHandler extends _FileHandlerBase<File> {
async readFileFromFileQuery(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 };
}
}
export const FileHandler = new _FileHandler();
export class _FileOrNullHandler extends _FileHandlerBase<File | null> {
async readFileFromFileQuery(fq: FileQuery): Promise<File | null> {
return orNull(() => FileHandler.readFileFromFileQuery(fq));
}
}
export const FileOrNullHandler = new _FileOrNullHandler();
FileHandler.readFileFromFileQuery(null!) // Promise<File>
FileOrNullHandler.readFileFromFileQuery(null!) // Promise<File | null>
FileHandler.readFiles(null!) // Promise<File[]>
FileOrNullHandler.readFiles(null!) // Promise<(File | null)[]>
// Some assumptions
type Path = string;
interface FileQuery {
path: string, flag?: string, encoding?: string | null
}
export interface File {
path: string, flag?: string, encoding: string | undefined | null, content: Buffer | string
}
interface Directory {
path: string, isDir: true
}
declare var FileQueryHandler: {
make(fq: FileQuery): FileQuery
getFromPath(s: string, b?: Omit<FileQuery, 'path'>): FileQuery;
}
declare var DirectoryHandler : {
readDirectory(a: Path | FileQuery) : FileQuery[]
}
type Omit<T, K> = Pick<T, Exclude<keyof T, K>>
function orNull<T>(fn: () => T) {
try {
return fn();
} catch (e) {
return null;
}
}
declare const PathHandler: {
getFromDirectory(d: Directory): FileQuery[];
}