【问题标题】:TypeScript validation of an exported array导出数组的 TypeScript 验证
【发布时间】:2018-07-29 13:57:44
【问题描述】:

我正在尝试导入如下所示的 config.ts 文件:

export default [
    {
        //Required
        sender: 'admin',
        mimeType: 'application/pdf',

        //Optional
        newEmailsOnly: true, // default: true
        renameCallback: (originalFilename: string) => 'test.pdf',
    },
    {
        ...
    }
];

我想将它导入到我的index.ts文件中,如果配置文件没有正确写入我希望它警告我,所以我有这个界面:

export interface Config {
    sender: string;
    mimeType: string;

    newEmailsOnly?: boolean;
    renameCallback?: (originalFilename: string) => string;
}

我知道我应该写一个declare module 'config',但我有点迷路,因为我要导出一个对象数组...

有人可以帮我吗?

【问题讨论】:

    标签: javascript typescript module typescript-typings


    【解决方案1】:

    我相信这就是您要找的:

    export const myConfig: Config[] = [
        {
            //Required
            sender: 'admin',
            mimeType: 'application/pdf',
    
            //Optional
            newEmailsOnly: true, // default: true
            renameCallback: (originalFilename: string) => 'test.pdf',
        }
    ];
    
    export interface Config {
        sender: string;
        mimeType: string;
    
        newEmailsOnly?: boolean;
        renameCallback?: (originalFilename: string) => string;
    }
    

    在打字稿中,您可以通过在类型后面加上[] 来表示x 的数组:

    A[];
    B[];
    Config[]

    【讨论】:

    • 正是我想要的。我认为这必须在d.tsfile 中完成。
    • d.ts 主要用于伴随没有类型概念的js 文件,而ts 文件包含所有类型信息。
    • 好的。这很方便。所以说js文件的时候不应该用declare这个关键字吧?
    • declare 不应直接在js 文件中使用,不。通常declare 仅用于告诉打字稿有关没有类型的外部js 库。假设一个 lib 将 SomeClass 添加到窗口,但它没有关联的类型 - 打字稿可能会抱怨 SomeClass 不存在,要解决这个问题,我可以 declare var SomeClass: any。这告诉 typescript “SomeClass 存在,但我不太了解它,让我使用它。” typescriptlang.org/play/…
    • 好吧,我不确定。感谢朋友的帮助
    猜你喜欢
    • 2020-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-29
    • 1970-01-01
    • 1970-01-01
    • 2013-02-28
    • 1970-01-01
    相关资源
    最近更新 更多