简体   繁体   中英

Hide function from js (typescript only function)

I have a javascript library, which defines types via index.d.ts. I'd like to expose a different API for javascript than for typescript.

It seems like if you want to hide something from typescript, you can just not define it in the.d.ts file. 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. Is there a way to implement typescript only functions in.d.ts or otherwise?

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.

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 . Your typescript is compiled to javascript. The types are basically just removed. Also there is no way to really hide something from typescript . Just because you have no types does not prevent you from calling a function.

However if you only want this for correct typing the correct way are generics. so if you have a get() function you can type it like this:

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

Then you can use it like getIt<Number>("...") from ts or just getIt("...") from js.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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