【问题标题】:Export symbol declaration in TypeScript在 TypeScript 中导出符号声明
【发布时间】:2018-09-23 06:28:47
【问题描述】:

在我正在处理的项目中,我使用符号来标记函数以确定代码是应该使用函数表达式本身还是调用它并使用返回值。目前看起来是这样的:

const shouldEvaluate: unique symbol = Symbol('evaluate');

interface FlaggableFunction extends Function {
    [shouldEvaluate]?: boolean
}

虽然这可行,但当我在配置中启用声明时,我收到错误 semantic error TS4033 Property '[shouldEvaluate]' of exported interface has or is using private name 'shouldEvaluate'.。如果我导出这个符号,它会起作用,但是它也会被导出到编译的 JS 中,这是我不想要的。有没有办法只将符号导出到声明文件,同时在编译的 JS 中保持私有?

到目前为止,我已经尝试过分别声明类型和初始化变量

export declare let shouldEvaluate: unique symbol;
shouldEvaluate = Symbol('evaluate');

但这给了我一个错误,即必须使用 const 声明唯一符号。我还尝试在索引签名中给出FlaggableFunction,如下所示:

interface FlaggableFunction extends Function {
    [key: unique symbol]: boolean
}

但这会引发TS1023 An index signature parameter type must be 'string' or 'number'.

【问题讨论】:

    标签: typescript


    【解决方案1】:

    有没有办法只将符号导出到声明文件,同时在编译的 JS 中保持私有?

    当您执行export declare let shouldEvaluate: unique symbol; 时,无论如何它都会公开。

    所以不,您不能使用属于公共类型的私有变量。

    您可以将所有内容保密。但这不是你想要的。

    【讨论】:

      【解决方案2】:

      更新:我意识到我可以轻松地将标志移动到一个单独的文件中并导出它们,因为在我的情况下,我更关心在入口文件中保留一个默认导出比我要暴露旗帜。下面是我之前的尝试,有点乱。


      这需要一些工作,但我已经找到了一种可行的解决方案。基本上,我将所有对这些符号的代码引用移到了它们自己的私有函数中,并使用对象字面量映射到这些符号。

      const shouldEvaluate: unique symbol = Symbol('evaluate');
      
      const flags: { [key: string]: symbol } = {
          evaluate: shouldEvaluate
      };
      
      // Switched to a single Flaggable type that takes a generic type instead of creating multiple so it an be passed into the setFlag function
      export type Flaggable<T> = T & {
          [shouldEvaluate]?: boolean
      }
      
      function setFlag(val: Flaggable<any>, flag: string) {
          const symbol: symbol = flags[flag];
          val[symbol] = true;
      }
      

      所以现在在导出的类中,我没有直接将符号设置为函数的属性,而是使用 setFlag 函数。

      export default class MyClass {
          setEvalFlag (func: Flaggable<Function>): Flaggable<Function> {
              setFlag(func, 'evaluate');
              return func;
          }
      }
      

      【讨论】:

      • 作为旁注,我也尝试使用 just 一个对象,但是将符号分配给类型为 unique symbol 的属性会引发错误。我提交了一个问题,因为这似乎是一个错误。 github.com/Microsoft/TypeScript/issues/23388
      猜你喜欢
      • 2017-05-31
      • 2016-12-06
      • 2017-11-28
      • 2020-11-29
      • 2020-06-29
      • 2018-07-19
      • 2021-09-28
      • 2018-10-27
      • 2020-03-22
      相关资源
      最近更新 更多