【问题标题】:Get exported function names from file in Typescript从 Typescript 中的文件中获取导出的函数名称
【发布时间】:2020-05-20 05:44:26
【问题描述】:

出于智能感知的目的,我需要从文件中获取导出的函数名称。

假设我们有以下具有一些功能的文件:

//demo.ts
export const foo = () => {};
export const bor = () => {};

现在让我们从文件中导入所有内容并将其传递给通用函数:

import * as demo from './demo'

function myGenericFunction<T>(module: T, functionName: ? ){
}

myGenericFunction(demo ,'foo');

问题是如何设置functionName的类型变成foo|bar

【问题讨论】:

    标签: typescript function generics types intellisense


    【解决方案1】:

    您可以像使用任何其他类型的密钥一样使用keyof T

    import * as demo from './demo'
    
    function myGenericFunction<T>(module: T, functionName: keyof T ){
    }
    
    myGenericFunction(demo ,'foo');
    myGenericFunction(demo ,'bor');
    myGenericFunction(demo ,'bar'); // error
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-02
      • 2021-04-11
      • 2021-09-28
      • 2019-02-18
      • 2020-01-19
      • 2018-10-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多