This workshop is for JavaScript developers who want to learn TypeScript.
TypeScript adds static types to JavaScript, which reduces bugs and speeds up development with autocompletion.
- Install NodeJS version 14+
- Install Visual Studio Code
- Install Git
- OPTIONAL: Install Gramex or Log into the IDE
In this exercise, you'll convert a JavaScript file into a TypeScript file and fix errors.
- Fork this repo into your namespace. Use
gitto clone your fork - Open
index.htmlin your browser and try out the game. (It has a bugs. Don't fix them yet)
- Run
npm install --save-dev typescriptto install TypeScript - Rename
script.jstoscript.ts(TypeScript) - Run
npm testto see the problems - Fix errors and hints in
script.tsusing Visual Studio Code. Specifically:- Run
npm install --save-dev @types/jqueryto infer jQuery types - In
Sprite, defineelas aHTMLELementtype - In
Sprite, definexandyasnumbertype - In
Sprite.constructor(), specify or auto-infer the types of all parameters.selectormust be astring. - In
Sprite.constructor(), tell TypeScript thatthis.elis not null. (Understand why)- Adding
!afterdocument.querySelector(selector)(non-null assertion operator) - Adding
as HTMLElementafterdocument.querySelector(selector)(type assertion) - Write custom code
- Adding
- In
Sprite.draw(), fix the error with$("body").addclass(...) - In
Sprite.sway(), fix the error withMath.random < 0.5 - In
Sprite.move(), specify or auto-infer the type of thedirectionparameter - In
Sprite.move(), fix the error withdirection !== "right"ordirection === "left" - In
document.querySelector("button.left")anddocument.querySelector("button.right")add event listeners only if they exist, using?.optional chaining
- Run
- Run
npm testto ensure that the problems are fixed
- If you're using Gramex, change
script.jstoscript.tsinindex.html. Run Gramex and play the game - If you're NOT using Gramex, run
tsc --strict script.ts. Openindex.htmlin your browser and play the game
- Commit and push the fixes to your fork. Check on Gitlab that CI/CD > Pipelines passes without errors
- Create an issue titled
Exercise submission. Add a link to your repo and submit the issue.
To mark a submission as correct:
- Check if the build errors pass
- Check if
Spritedefinesel: HTMLElement; x: number; y: number - Check for
constructor(selector: string, x: number, y: number)signature - Check for
addClassinstead ofaddclassindraw() - Check for
Math.random()instead ofMath.randominsway() - Check that
move()mentions"left"and"right" - Check for click events added to
.leftand.rightthat call.move("left")and.move("right")
