Types in JavaScript
February 29, 2024 ยท View on GitHub
Types in JavaScript
If you love types but not transpiling, then using TypeScript itself won't be your cup of tea, but there are other approaches you can take to get pretty close.
Participate
Join our GitHub discussions!
This repo exists mainly to promote a discussion around this topic โ exchange experiences, share best practices and tips and ask for help on tricky parts. The discussions is found in the GitHub discussions of this repo
Is there a readme badge?
Yes! If you use types in plain JS in your project, you can include thise badge in your readme to let people know that your code is typed without relying on TypeScript syntax.
[](https://github.com/voxpelli/types-in-js)
How to use types in JavaScript
TypeScript supports JavaScript and it supports quite a few JSDoc annotations to help you type your JS code (some, like @deprecated, is even used in TS-code).
Since TypeScript is what drives the JavaScript tools in Visual Studio Code and its intellisense the implementation is actually used more than one would initially guess.
Getting started
-
Add a
tsconfig.jsonwith eg.allowJs: trueor add a(Turns out thatjsconfig.jsoninstead, which impliesallowJs: truejsconfig.jsonimplies a lot more than justallowJs: trueand as such is not recommended. See discussion at https://github.com/voxpelli/types-in-js/discussions/25) -
Then point it to your javascript files by using
filesand/orincludeproperties. -
Lastly either set
checkJs: truein it, to have all of those files checked, or selectively add// @ts-checkto the top of the files you want to check. -
(optional) Add some other useful / needed configurations, see TSConfig tips.
-
(optional) Install
typescriptlocally in your project (npm install typescript), then validate your project usingnpx tsc(tscis the name of the CLI supplied bytypescript).tsccan preferably be run as a part of your test scripts, locally and on CI. See CI / linting tips
Articles around using types with JavaScript
TSConfig tips
See open discussion as well as base configs to extend from.
CI / linting / additional tools
See open discussion
JSDoc syntax tips
There's a cheatsheet available
Managing third party dependencies
See open discussion