Closed goldbergyoni closed 2 years ago
Hi @goldbergyoni -- I'm not the maintainer but I figured I'd answer since I just did this myself.
You do need to run typegen yourself, and store the file somewhere it's accessible to your source code.
Then your snippet becomes this:
import { Client as MyApiClient } from './path/to/generated/typefile'
const clientGenerator = new OpenAPIClientAxios({
definition: path.join(__dirname, '../openapi.json'),
});
const mailerAPI = await clientGenerator.getClient<MyApiClient>();
mailerAPI.{now you see methods here}
The constructor for the main class can't be typed with your custom types, unfortunately. Even if you pass it when you call init(), that custom typing won't be saved that way. The answer is to keep a reference to the instance it returns, which is associated with your custom types.
getClient()
is the better way to go than init()
, though, because it still calls init
under the hood for an instance that hasn't been initialized yet, but the returned instance is a singleton -- so if you ever call it again, you're getting the same object back without re-initializing.
Hope this helps!
@goldbergyoni, you should give a help to your hinting tool how to resolve client type.
Example using jsDoc
:
pet.types
is pet.types.d.ts
that was generated by typegen
tool
example.js
import { OpenAPIClientAxios } from './openapi-client-axios'
/** @type {() => import("./pet.types").Client } **/
const getMyOACA = () => {
const clientInstance = new OpenAPIClientAxios();
return clientInstance;
}
const client = getMyOACA();
client.updatePetById()
and hints will work
Great initiate here, thank you.
Question - I'm using JS and followed the docs, but can't see any types suggestion in vscode. Here what I've done:
Should I run typegen manually? What is the workflow for JS scenario (not TS) given that most IDE knows to conclude d.ts file definitions even when coding with JS?