DH의 개발 공부로그
[TypeScript] JavaScript 슈팅게임에 TypeScript 적용하기! #3 - start() & SpaceShip 본문
TypeScript
[TypeScript] JavaScript 슈팅게임에 TypeScript 적용하기! #3 - start() & SpaceShip
DeveloperDH 2023. 2. 23. 22:37728x90

start() & SpaceShip
이번에 TypeScript로 변환할 부분은 Game안에 start 함수와 SpaceShip부분 입니다.
Game안의 start함수에 사용자가 조종을 할 spaceShip가 인스턴스 되기 때문에 start와 함께spaceShip를 같이 묶어서 변환을 해보겠습니다.
우선 기존 JavaScript 코드 먼저 봐보겠습니다.
1. spaceShip
class SpaceShip {
constructor(game, x, y) {
this.game = game;
this.lev = 1;
this.x = x;
this.y = y;
}
update() {
if (score >= this.lev * 15) {
this.lev += 1;
}
}
}
spaceShip의 자바스크립트 코드는 위와 같습니다.
이것을 다음과 같이 변환을 해주었습니다.
class SpaceShip {
constructor(
public game: Game;
public x: number;
public y: number;
public lev: number;
) { }
public update() {
if (score >= this.lev * 15) {
this.lev += 1;
}
}
}
2. start()
class Game {
start() {
this.changeScreen("game");
this.spaceShip = new SpaceShip(
this,
this.canvas.width / 2 - 32,
this.canvas.height - 84 // 우주선 크기 & 바닥 공간 20
);
this.loadImage();
this.keyEvent();
this.createMonster();
this.main();
}
}
기존 코드를 ts 파일로 옮기면 this.spaceShip부분이 오류가 뜹니다.
오류의 내용은 다음과 같습니다.
Property 'spaceShip' does not exist on type 'Game'
바로 spaceShip이 Game에 존재하지 않는다는 뜻입니다.Game에서 spaceShip이 따로 선언을 하거나 타입을 지정을 해주지 않고 사용을 했기 때문에
오류가 생긴 것이기 때문에 spaceShip타입을 지정을 해주어야 합니다.
class Game {
public canvas: HTMLCanvasElement;
public ctx: CanvasRenderingContext2D;
public spaceShip?: SpaceShip | null
constructor() {
...
}
public start() {
this.changeScreen("game");
this.spaceShip = new SpaceShip(
this,
this.canvas.width / 2 - 32,
this.canvas.height - 84, // 우주선 크기 & 바닥 공간 20
1 // lev
);
this.loadImage();
this.keyEvent();
this.createMeteor();
this.main();
}
}728x90
'TypeScript' 카테고리의 다른 글
| [TypeScript] JavaScript 슈팅게임에 TypeScript 적용하기! #5 - DOM 조작에 대한 Type Narrowing (0) | 2023.02.25 |
|---|---|
| [TypeScript] JavaScript 슈팅게임에 TypeScript 적용하기! #4 - 이미지 부분 변환하기! (0) | 2023.02.24 |
| [TypeScript] JavaScript 슈팅게임에 TypeScript 적용하기! #2 - Canvas 활용하기 (0) | 2023.02.23 |
| [TypeScript] JavaScript 슈팅게임에 TypeScript 적용하기! #1 (0) | 2023.02.22 |
| [TypeScript] 타입스크립트 인터페이스 - Interface (0) | 2023.02.10 |
Comments