Skip to content
This repository has been archived by the owner on Jul 15, 2022. It is now read-only.

Typescript Migration Tips

Valentin D. Pinkman edited this page Aug 11, 2021 · 4 revisions

Preparation (not needed for PRs)

Prioritize module that has less "import" so that types for all the dependencies are provided. madge comes in handy on this topic. Generates dependency graph image and start converting from modules in green. One catch is that it doesn't support module resolution so doesn't work well with desktop repo that uses ~/renderer/... for example.

brew install gts
brew install graphviz

npx madge --image graph.svg src # replace src to specific path

(this step was used to determine the depth of dependencies and where to start from, if you are working on a PR, you can still use madge if you have lots of dependencies but it should not be required)

How to Migrate an ongoing PR

Here are the steps to make your current PR work with the new TypeScript Migration:

git checkout develop
git pull upstream master
git checkout your-branch
git rebase master

Conflicts

There might (and there will be) conflicts. Always make sure the old .js files are matched to the new .ts files (sometimes git will understand the renaming, sometimes it won't). Then if you have new .js files that have not been converted yet, use the codemod.
Make sure to fix the old flow types.
Always run yarn build to make sure there are no compilation errors.

Code mod

GitHub - Khan/flow-to-ts: Convert flow code to typescript We have been using the codemod made by KhanAcademy to, more or less painlessly, convert our flow typed javascript files to typescript. Most of the heavy lifting was done with the codemod, but we had to come back and fixes many types / errors. For a quick usage of the codemod, here is how we used it

npx @khanacademy/flow-to-ts --write --delete-source src/**/*.js

This cli also supports --prettier flag which uses prettier as a formatter but it didn't work well for some reasons when we worked on ledgerjs. Make sure to run yarn lint --fix before commit.

Ignore errors

Utilize @ts-expect-error annotation when you cannot figure out how to make TypeScript compiler happy. We can come back and catch these comments on the reviewing process.

@ts-expect-error Describe what error to expect here or reason to ignore

Casting

Sometimes mocked object (often used in test code) doesn't have all the properties defined in its type and compiler throws error where the obj is in use. In that case, utilize type casting instead of @ts-expect-error.

const account = { name: "Account 1" }
const name = getAccountName(account as Account) // <-
expect(name).toBe("Account 1")

Third-Party modules that doesn't come with definition files

Try to find module in https://definitelytyped.org/

yarn add @types/module-name -D

If it doesn't exists, we need to create custom definition file typically under src/@types/.