简体   繁体   English

从 js 中隐藏 function(仅限打字稿功能)

[英]Hide function from js (typescript only function)

I have a javascript library, which defines types via index.d.ts.我有一个 javascript 库,它通过 index.d.ts 定义类型。 I'd like to expose a different API for javascript than for typescript.我想为 javascript 公开与 typescript 不同的 API。

It seems like if you want to hide something from typescript, you can just not define it in the.d.ts file.看起来如果你想从 typescript 中隐藏一些东西,你不能在 .d.ts 文件中定义它。 Is it possible to do it the other way around?是否可以反过来做? As far as I can tell, the.d.ts file can only have definitions, and no implementation.据我所知,.d.ts 文件只能有定义,没有实现。 Is there a way to implement typescript only functions in.d.ts or otherwise?有没有办法实现 typescript 仅功能 in.d.ts 或其他?

For example, I'd like to expose a generic get() function for js only usage, and typed getString and getInt wrappers that are only defined for typescript.例如,我想公开一个仅用于 js 的通用 get() function,并键入仅为 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];
  }
}

This is conceptionally not possible because at runtime there is no typescript .这在概念上是不可能的,因为在运行时没有 typescript Your typescript is compiled to javascript.您的 typescript 编译为 javascript。 The types are basically just removed.这些类型基本上只是被删除了。 Also there is no way to really hide something from typescript .也没有办法真正从 typescript 隐藏一些东西 Just because you have no types does not prevent you from calling a function.仅仅因为您没有类型并不能阻止您调用 function。

However if you only want this for correct typing the correct way are generics.但是,如果您只想正确输入,则正确的方法是 generics。 so if you have a get() function you can type it like this:所以如果你有一个get() function 你可以这样输入:

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

Then you can use it like getIt<Number>("...") from ts or just getIt("...") from js.然后你可以像 ts 中的getIt<Number>("...")或 js 中的getIt("...")一样使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM