Search code examples
typescripttypescript-typingstypescript3.0

Does using the unknown type in a typescript library force all dependents to use typescript version 3.0 or greater?


I’m wondering if using unknown in my exported types in a package distributed via npm forces any code which depends on that library to use typescript 3.0. unknown was added in typescript 3.0 (https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-0.html). I’m defining and exporting a class which has a method which takes unknown as an argument and the unknown keyword shows up in the generated d.ts file.

Can older typescript compilers handle the unknown type in the generated d.ts or am I forcing everyone who uses my package to use typescript 3.0 or later? Should I use any instead? Is there any way to “shim” this missing type for older typescript versions?


Solution

  • Older TypeScript compilers cannot handle unknown. Here is a shim technique that surprisingly works.

    1. Create the following shim.d.ts file.
    2. Reference that file in your library's main file.

    shim.d.ts

    declare global {
        // @ts-ignore
        export type unknown = any;
    }
    
    export { }
    

    index.ts

    /// <reference path="shim.d.ts" />
    
    /**
     * This is a tiny demo function that returns `unknown`. Your actual module
     * could include a lot more functionality.
     */
    export default (): unknown => {
        return {} as unknown;
    };
    

    When your library's consumer compiles with an older version of TypeScript, the compiler will create a new type called unknown that is an alias for any. When your library's consumer compiles with a later version of TypeScript, the compiler will not create a new type, but because of that sneaky @ts-ignore, the compiler will also not complain.

    Here is a demo of this at work.

    As jcalz points out in the comments, instead of any we could alias {} | null | undefined | void instead.