Home > Enterprise >  recursive type become any after emit declaration, need implicit solution
recursive type become any after emit declaration, need implicit solution

Time:10-27

I am creating a npm package, basically it is a function that return an object that return the return of the function itself

export const chainCreator = () => {
    return {
        chain: () => {
            return chainCreator()
        },
        end: () => {
            return 'end'
        },
    }
}

enter image description here

so far so great, the type is ok

but thing break when I build it: enter image description here

it returns any type instead, so this is a big no

There is a solution, by typing it explicitly (type annotations)

type chainCreator = {
    (): { chain: () => ReturnType<chainCreator>; end: () => string }
}
export const chainCreator: chainCreator = () => {
    return {
        chain: () => {
            return chainCreator()
        },
        end: () => {
            return 'end'
        },
    }
}

enter image description here This works as expected, however, I prefer an implicit solution(type inference), because it is more automated, less maintenance is needed and more accurate.

this is my config

{
    "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/**/*"]
}

so my question is, is there any implicit solution for recursive function like this?

CodePudding user response:

No, TypeScript doesn't currently have a way to emit a reasonable declaration file for an anonymous recursive type. There's a very old open issue at microsoft/TypeScript#463 discussing this problem, and while there have been some improvements over any in IntelliSense (you get those ellipses ... when things are too long), the type emitted to declaration files is still just any.

There's a suggestion at microsoft/TypeScript#44045 to support generating automatic type aliases in declaration files to give a name to anonymous types that are hard to expand either because they are very large or recursive and therefore infinite. It's not clear when or if something like this will be implemented. It wouldn't hurt to give that issue a

  • Related