Managing untyped third party dependencies. #7
Raynos
started this conversation in
Best Practices / Patterns
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
In a project using JSDoc, you will often want to avoid the
anytype. A common place where you find this is when yourequire('tape')or any other dependency that does not come with either anindex.d.tsor (valid) JSDoc annotations internally.Some libraries ship with type defintions, for example
aws-sdkso they do not need to be managed by you.There are two ways of managing the type definitions of your dependencies. You can either vendor them or you can manage them by using
npmInstalling type definitions with npm
You can install the types of library by using
npm install @types/tapeand it will fetch the types from DefinitelyTypedThere are pros & cons to this approach.
Pros
npm install @types/node. The node types are not perfect but they are still non-trivial and simpler then vendoring them.Cons
jsconfig.jsonor version of TypeScript, they may not be compatible.eslint/tsc+jsconfig.jsonVendoring type definitions.
Alternatively to installing type definitions from
npmyou can actually include type definitions for dependencies in your own project. I personally use atypesor_typesdirectory.You can tell typescript in a
jsconfig.jsonto use these types at type check timeYou specify that all unkown modules
*comes from_types. Unfortunately any modules that are "scoped" and have a/in the name have to be rewritten in thex__ystyle,DefinitelyTypedhas a similar limitation.The
_typesdirectory contains one directory per third party dependency and inside there's anindex.d.ts; this layout is incredibly similar to the layout of for example@types/tapefrom npm. The best way to get started with vendoring is to install a type defintion from@types/xyzand then copy it into_typesand then delete that@types/xyzdependency.Once a type definition is vendored you can include in your
jsconfig.jsonThis will make
tsctype check the third party dependencies and apply your typescript configuration rules against your dependencies. Secondly, once included,eslintwill also lint your third party dependency configuration.I've found this tooling integration to especially helpful in enforcing the
no-explicit-anyrule, which annoyingly get's "cheated" by the type definitions in@types/nodefor some nodejs builtins.Pros
tsc/eslintget applied to your dependencies. Your dependencies are no longer "less strict" then your app code in terms of type safety.Cons
jsconfig.jsonnpm install @types/node.@raynos/typespackage and putting them all in there. Don't do that, avoid this temptation.Beta Was this translation helpful? Give feedback.
All reactions