Adapting One Old UI Components Library To Work In TypeScript Code

TypeScript type definitions

Type definitions

one simple `sample.js` module might look like this
standard way to declare types for TypeScript is to create an appropriate `.d.ts` module

Our JavaScript library

  • We would be able to import this package during the new repository initialization. This will allow controlling the version and simplify the refactoring during the version update.
  • We would stop copy-pasting the same code again and again.
  • Type definitions is a great documentation source. I bet developers would prefer to select the method from IntelliSense suggestions rather than go to the web page with all API descriptions and copy the method name.

So what is wrong?

depending on the value, the button will be rendered in a specific size and color palette
  1. We want the global variable ui to be accessible without having to import anything.
  2. We want our UI components definitions to be available without having to import anything as well.
  3. We want to use predefined constants and objects for UI components by importing them from our types package. There should not be any conflict to assign some type from the library in this case.

Start from the scratch

simple notification API allows assigning a text message and buttons
we highlight a button according to the type
we call a global API to show the notification dialog without custom button configuration
we simply add a new variable into the global namespace
all the notifications API is collected under the Notification interface
always emit declaration files
don’t forget to set up a build step for your package to compile TypeScript files

Using the values

we want to show notifications with the button of Danger type
we use composite export to create an alias for objects under the namespace
we export UiCore, and now it is available from the outside

Covering edge cases

TS2503: Cannot find namespace ‘UiCore’
we create types from the existing namespace using the type alias syntax
the different syntax for each case

Conclusion

  • Create and set up a new NPM package.
  • Describe the whole interface supported by the JavaScript library you want to write type definitions for.
  • Declare the global object that is being injected into window.
  • Create a namespace made of objects you have defined already — you will use it for import statements.
  • Create a namespace made of types based on the previous namespace. It will be located in the global scope.
  • Verify that we assigned the same name for both namespaces.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store