调用在同一对象内定义的函数

时间:2019-01-14 02:25:19

标签: typescript

我正在尝试创建一个对象,该对象本身会调用函数,但是打字稿似乎对该对象中的最后一个函数引发了一些问题。

这是输入和输入:

import * as fs from 'fs-extra';

enum T {
    FileQuery = 'FileQuery',
    File = 'File',
    FileJSON = 'FileJSON'
}

interface FileQuery {
    path: string;
    encoding: string;
}

interface File {
    path: string;
    encoding: string;
    content: string;
}

interface FileJSON {
    path: string;
    encoding: string;
    content: string;
    data: any;
}

这是代码本身

const f = {
    [`${T.FileQuery}To${T.File}`]: async (fileQuery: FileQuery): Promise<File> => {
        const { path, encoding } = fileQuery;
        const content = await fs.readFile(path, encoding);
        return { ...fileQuery, content }
    },
    [`${T.File}To${T.FileJSON}`]: (file: File): FileJSON => {
        const data = JSON.parse(file.content);
        return { ...file, data }
    },
    [`${T.FileQuery}To${T.FileJSON}`]: (fileQuery: FileQuery): FileJSON => {
        const file = f[`${T.FileQuery}To${T.File}`](fileQuery)
        return f[`${T.File}To${T.FileJSON}`](file);
    }
}

也尝试过这种方法,但也没有用:

const f = {
    async  [`${T.FileQuery}To${T.File}`] (fileQuery: FileQuery): Promise<File> {
        const { path, encoding } = fileQuery;
        const content = await fs.readFile(path, encoding);
        return { ...fileQuery, content }
    },
    [`${T.File}To${T.FileJSON}`] (file: File): FileJSON {
        const data = JSON.parse(file.content);
        return { ...file, data }
    },
    [`${T.FileQuery}To${T.FileJSON}`] (fileQuery: FileQuery): FileJSON {
        const file = f[`${T.FileQuery}To${T.File}`](fileQuery)
        return f[`${T.File}To${T.FileJSON}`](file);
    }
}

但这确实可以正常工作,而不会出现类型错误:

const f = {}

f[`${T.FileQuery}To${T.File}`] = async (fileQuery: FileQuery): Promise<File> => {
    const { path, encoding } = fileQuery;
    const content = await fs.readFile(path, encoding);
    return { ...fileQuery, content }
}

f[`${T.File}To${T.FileJSON}`] = (file: File): FileJSON => {
    const data = JSON.parse(file.content);
    return { ...file, data }
}

f[`${T.FileQuery}To${T.FileJSON}`] = (fileQuery: FileQuery): FileJSON => {
    const file = f[`${T.FileQuery}To${T.File}`](fileQuery)
    return f[`${T.File}To${T.FileJSON}`](file);
}

0 个答案:

没有答案