I am currently in the process of developing an npm package. This package consists of a function that returns an object, which itself returns the result of the original function.
export const chainCreator = () => {
return {
chain: () => {
return chainCreator()
},
end: () => {
return 'end'
},
}
}
https://i.sstatic.net/VJM4k.png
Everything was going smoothly until I tried building it:
https://i.sstatic.net/HTVU7.pngInstead of returning the expected type, it was returning any
, which is not ideal.
The solution lies in explicitly typing it using type annotations:
type chainCreator = {
(): { chain: () => ReturnType<chainCreator>; end: () => string }
}
export const chainCreator: chainCreator = () => {
return {
chain: () => {
return chainCreator()
},
end: () => {
return 'end'
},
}
}
https://i.sstatic.net/r15EB.png This approach works as intended, but personally, I prefer an implicit solution for better automation, reduced maintenance, and improved accuracy.
This is the configuration I have set up:
{
"compilerOptions": {
"isolatedModules": true,
"module": "commonjs",
"declaration": true,
"esModuleInterop": true,
"sourceMap": true,
"noImplicitAny": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"target": "esNext",
"allowJs": true,
"baseUrl": "src",
"emitDeclarationOnly": true,
"outDir": "dist",
"paths": {
"*": ["*"]
},
"typeRoots": ["./node_modules/@types"]
},
"include": ["src/**/*"]
}
My question now is, is there any implicit solution available for recursive functions like this one?