I’m trying to learn TypeScript but have an issue that I struggle to resolve.
function makeClient(api, kubeconfig: string) {
const config = new k8s.KubeConfig()
if (kubeconfig) {
config.loadFromFile(kubeconfig)
} else {
config.loadFromCluster()
}
return config.makeApiClient(api)
}
I need to create a function that wraps another function from a library (Kubernetes client), what I want to do is to allow two arguments to my function: api
and kubeconfig
.
If kubeconfig
is set, I will create a client for the given api
argument using the given file.
If kubeconfig
is not set or empty/null, I will create an in-cluster client for the given api
.
My issue is that I somehow need to provide a type for the api
parameter. The library provides some types, but when I look at the types of the makeApiClient
function argument, I get this:
export declare class KubeConfig {
// ...
makeApiClient<T extends ApiType>(apiClientType: ApiConstructor<T>): T;
// ...
}
export interface ApiType {
defaultHeaders: any;
setDefaultAuthentication(config: api.Authentication): void;
}
declare type ApiConstructor<T extends ApiType> = new (server: string) => T;
How should I provide a type to my api
argument so that it allows only supported values?
CodePudding user response:
Why not make your wrapping function also generic? Then you can just use the type that is expected by makeAPICLient
. Like this:
function makeClient<T extends k8s.ApiType>(api: k8s.ApiConstructor<T>, kubeconfig: string | null): T {
const config = new k8s.KubeConfig()
if (kubeconfig) {
config.loadFromFile(kubeconfig)
} else {
config.loadFromCluster()
}
return config.makeApiClient(api)
}