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
git
to clone your fork - Open
index.html
in your browser and try out the game. (It has a bugs. Don't fix them yet)
- Run
npm install --save-dev typescript
to install TypeScript - Rename
script.js
toscript.ts
(TypeScript) - Run
npm test
to see the problems - Fix errors and hints in
script.ts
using Visual Studio Code. Specifically:- Run
npm install --save-dev @types/jquery
to infer jQuery types - In
Sprite
, defineel
as aHTMLELement
type - In
Sprite
, definex
andy
asnumber
type - In
Sprite.constructor()
, specify or auto-infer the types of all parameters.selector
must be astring
. - In
Sprite.constructor()
, tell TypeScript thatthis.el
is not null. (Understand why)- Adding
!
afterdocument.querySelector(selector)
(non-null assertion operator) - Adding
as HTMLElement
afterdocument.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 thedirection
parameter - 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 test
to ensure that the problems are fixed
- If you're using Gramex, change
script.js
toscript.ts
inindex.html
. Run Gramex and play the game - If you're NOT using Gramex, run
tsc --strict script.ts
. Openindex.html
in 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
Sprite
definesel: HTMLElement; x: number; y: number
- Check for
constructor(selector: string, x: number, y: number)
signature - Check for
addClass
instead ofaddclass
indraw()
- Check for
Math.random()
instead ofMath.random
insway()
- Check that
move()
mentions"left"
and"right"
- Check for click events added to
.left
and.right
that call.move("left")
and.move("right")