从js中隐藏函数(仅typescript函数)



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

如果你想从typescript中隐藏一些东西,你可以不在.d.ts文件中定义它。有可能反过来做吗?据我所知,.d.ts文件只能有定义,不能有实现。有没有一种方法可以在.d.ts或其他地方实现只使用typescript的函数?

例如,我想公开一个只用于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];
}
}

这在概念上是不可能的,因为在运行时没有类型脚本!您的typescript被编译为javascript。这些类型基本上只是被删除了。此外,没有办法真正从typescript隐藏某些东西。没有类型并不能阻止您调用函数。

然而,如果你只想正确地键入,正确的方法是泛型。因此,如果你有一个get()函数,你可以这样键入:

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

然后,您可以像ts中的getIt<Number>("...")或js中的getIt("...")一样使用它。

最新更新