【问题标题】:Tell TypeScript that pragmatically created exports exists in module告诉 TypeScript 实用创建的导出存在于模块中
【发布时间】:2018-04-13 11:31:14
【问题描述】:

如果以编程方式创建导出:

例子:

const peeps = ['peep1', 'peep2', ...]
peeps.forEach(peep => exports[peep] = mainMethod.bind(null, peep))

告诉 TypeScript 这些方法的最佳方式是什么?目前,当我尝试按预期导入它们时,它们没有显示为导出。如何将它们定义为 TypeScript 可以理解的导出?

我试图避免

export const peep1 = mainMethod.bind(null, 'peep1')
export const peep2 = mainMethod.bind(null, 'peep2')

编辑: 我可能需要说清楚。它工作正常,我对导出本身没有问题,我有一个问题,因为它们是务实地创建的,vscode 不知道它们存在,因为在设计时所述导出不在文件中。我正在尝试让 TypeScript 在设计时识别所述导出。

【问题讨论】:

  • 你使用什么模块系统?该导出是您模块中唯一的导出吗?

标签: typescript typescript-typings


【解决方案1】:

问题的第一部分是构造一个对象,该对象具有在字符串数组中定义的属性。

// The helper insures we get the type of peeps as ('peep1' | 'peep2')[] not string[]
const peeps = helper('peep1', 'peep2'); 
// Define a type that maps the constants to properties
let methods : {
    [P in typeof peeps[number]]: () => void
} = {} as any;
// Add the members to the object
peeps.forEach(peep => methods[peep] = mainMethod.bind(null, peep))

function helper<T extends string>(...array: T[]) : T[]{
    return  array;
} 

根据您的模块系统,您可以通过以下两种方式之一导出 methods 对象。

如果您使用amdcommonjsumd,您可以使用导出赋值:

// methods.ts
// code above 
export = methods;

//usage.ts
import * as m from './aaa'
m.peep1();

对于其他模块系统,您可以使用默认导出:

// methods.ts
// code above 
export default methods;

//usage.ts
import m from './aaa'
m.peep1();

【讨论】:

    【解决方案2】:

    我想通了。我想我只需要添加:

    declare export function peep1(age:number):any;
    declare export function peep2(age:number):any;
    

    基本上,我必须为它编写一个 d.ts 文件,因为它们是动态创建的导出。

    【讨论】:

      猜你喜欢
      • 2017-09-25
      • 2021-01-31
      • 2022-01-08
      • 2017-12-02
      • 1970-01-01
      • 2020-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多