【问题标题】:Hide function from js (typescript only function)从 js 中隐藏功能(仅限打字稿功能)
【发布时间】:2021-07-16 04:35:17
【问题描述】:

我有一个 javascript 库,它通过 index.d.ts 定义类型。我想为 javascript 提供与 typescript 不同的 API。

似乎如果你想从打字稿中隐藏一些东西,你不能在 .d.ts 文件中定义它。是否可以反过来做?据我所知, .d.ts 文件只能有定义,没有实现。有没有办法在 .d.ts 或其他方式中实现仅打字稿功能?

例如,我想公开一个仅用于 js 的通用 get() 函数,并键入仅为 typescript 定义的 getString 和 getInt 包装器。

index.d.ts

declare module 'example' {
  export function getConfig(): Config;

  export interface Config {
    // have these wrap get() and return null if the type is wrong
    getString(name: string): string | null; 
    getInt(name: string): int | null;
  }
}

index.js

module.exports = {
  getConfig() {
    return new Config({
      testString: "test",
      testInt: 12,
    })
  }
}

Config.js

class Config {
  constructor(configObject) {
    this.configObject = configObject;
  }

  get(index) {
    return this.configObject?[index];
  }
}

【问题讨论】:

    标签: javascript typescript .d.ts


    【解决方案1】:

    这在概念上是不可能的,因为在运行时没有打字稿! 您的打字稿被编译为 javascript。这些类型基本上只是被删除了。 也没有办法真正从打字稿中隐藏一些东西。仅仅因为你没有类型并不能阻止你调用函数。

    但是,如果您只希望它用于正确键入,那么正确的方法就是泛型。所以如果你有一个get() 函数,你可以这样输入:

    function getIt<T extends String | Number>(name: string) : T {
      ...
    }
    

    然后你可以像 ts 中的 getIt&lt;Number&gt;("...") 或 js 中的 getIt("...") 一样使用它。

    【讨论】:

    • 对泛型的好建议,我没有考虑过这种方法。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 2020-10-04
    • 1970-01-01
    • 1970-01-01
    • 2020-04-25
    • 2021-06-30
    • 1970-01-01
    相关资源
    最近更新 更多