Oh yeah... TypeScript...
Tags that this post has been filed under.
So, I briefly learned about TypeScript over a year ago, but I think it was a little early in my experience as a developer for things to stick. Sigh. I guess it’s time to actually learn TS.
Looking for an over-simplified (likely incomplete) intro to TS? Carry on.
Formal (pinky out) definition:
TypeScript is a typed superset of JavaScript that compiles to plain JavaScript.
Great, but what does that actually mean?
Problem:
One common challenge for developers (specifically of JS) is type errors (due to the dynamically typed nature of the language so I’m told). A certain type of value was used where a different kind of value was expected.
This parameter was meant to be a number, but a string was received instead.
This object needs to have certain types of properties, but it doesn’t.
Solution:
TypeScript comes to the rescue because it catches type errors at build time instead of when the program is run. When I say ‘at build time’, to me it just means you get those red squiggly lines in your IDE (ahem VSCode) before the JS file is actually run.
But why? Some might say TS is simply for the developer experience (dx), but if it helps eliminate issues early, customers get their features more quickly and with stability, right?
So, the main arguments that I perceive are:
- reduced errors
- code faster
It’s just JavaScript! Instead of .js, just change all of your files to .ts. Boom. Done. Not so fast… The browser doesn’t run TypeScript. It understands JavaScript.
If you are out and about and encounter a browser, do not attempt speaking TypeScript to it. It might throat punch you in the face. It desires/wants (craves even) JavaScript.
Install:
To actually do the TypeScript, you must firstly install it (either globally on your machine or locally on a project).
npm install -g typescript # gobally
npm install -D typescript@latest # within a project
Initialize:
Next, it needs to be initialized. This is simply a configuration file that tells TypeScript how you like your Javascript plated.
tsc --init # generates tsconfig.json with defaults
Here are some settings that I like to use in the tsconfig file. These are personal preference.
{
"compilerOptions": {
"outDir": "./dist",
"rootDir": "./src",
"target": "ES2022",
"module": "node16",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true
},
"include": ["src/**/*"]
}
Compile:
When you have written something worth running, the code must then be compiled (converted) to plain old JavaScript.
tsc # uses settings from tsconfig.json
Now go build something.