У меня проблемы с кодом. Подпись индекса машинописного текста, которую я написал для своего кода:
const ships: { [index: string]: Ship } = {};
Что является частью этого блока кода:
recieveAttack(e: any) {
let target: string;
const location = document.getElementById(e.target.id);
const ships: { [key: string]: Ship } = {};
console.log(location.hasChildNodes());
if (location.hasChildNodes()) {
target = e.currentTarget.children[0].getAttribute('data-ship-type');
}
console.log(location.classList.contains('occupied'));
if (location.classList.contains('occupied')) {
console.log(target);
console.log('hit', ships[target]);
ships[target].hit(e.target.id);
} else {
this.miss(e.target.id);
}
}
приводит к тому, что мои тесты (написанные на jasmine) проходят, но код, который когда-то работал правильно, терпит неудачу по какой-то неизвестной причине. Однако, если я уберу эту строку кода, тесты завершатся ошибкой с кодом, который выдает:
{
"message": "TypeError: shipContainer is null\nat spec/index_spec.ts:127:13\n\nShip.prototype.renderShip/<@spec/index_spec.ts:127:13\nShip.prototype.renderShip@spec/index_spec.ts:118:9\n@spec/index_spec.ts:463:5\n@spec/index_spec.ts:457:2\n__webpack_require__@spec/index_spec.ts:20:12\n@spec/index_spec.ts:374:68\n__webpack_require__@spec/index_spec.ts:20:12\n@spec/index_spec.ts:69:18\n@spec/index_spec.ts:1:11\n",
"str": "TypeError: shipContainer is null\nat spec/index_spec.ts:127:13\n\nShip.prototype.renderShip/<@spec/index_spec.ts:127:13\nShip.prototype.renderShip@spec/index_spec.ts:118:9\n@spec/index_spec.ts:463:5\n@spec/index_spec.ts:457:2\n__webpack_require__@spec/index_spec.ts:20:12\n@spec/index_spec.ts:374:68\n__webpack_require__@spec/index_spec.ts:20:12\n@spec/index_spec.ts:69:18\n@spec/index_spec.ts:1:11\n"
Блок кода, на который указывает ошибка:
renderShip(): HTMLElement {
const ship: any[] = this.createShip();
const shipContainer: HTMLElement = document.querySelector(`#${ this.type() }`);
ship.forEach((value: string, index: number) => {
const section: HTMLElement = document.createElement('div');
section.setAttribute('draggable', 'true');
section.setAttribute('aria-grabbed', 'false');
section.setAttribute('data-direction', 'horizontal');
section.setAttribute('data-ship-type', this.type());
section.classList.add('ship');
section.classList.add(this.type());
section.id = this.type() + String(index);
shipContainer.appendChild(section);
});
shipContainer.addEventListener('click', () => {
const ship = shipContainer.children;
for (let i = 0; i < ship.length; i = i + 1) {
ship[i].setAttribute('aria-grabbed', 'true');
}
});
shipContainer.setAttribute('data-direction', 'horizontal');
shipContainer.addEventListener('dragstart', (e: any) => {
drag(e);
});
return shipContainer;
}
в частности эта строка:
const shipContainer: HTMLElement = document.querySelector(`#${ this.type() }`);
Я должен указать, что я использую jasmine-jquery для фикстур. Код code code shipContainer должен указывать на 1 из серверных кораблей, динамически добавляемых в дом, в зависимости от длины корабля.
Модуль кораблей
import { Ship } from './ship';
export module Ships {
export const patrol: Ship = new Ship(2);
export const destroyer: Ship = new Ship(3);
export const submarine: Ship = new Ship(3);
export const battleship: Ship = new Ship(4);
export const carrier: Ship = new Ship(5);
carrier.renderShip();
battleship.renderShip();
submarine.renderShip();
destroyer.renderShip();
patrol.renderShip();
}
Я понятия не имею, почему одна простая строка кода приводит к конфликту моего кода с моим тестом. Если есть сигнатурный индекс, все работает нормально, но тогда я не могу вызвать метод попадания кораблей[цель]. И, если его там нет, я сталкиваюсь с неудачными тестами. Мы будем очень признательны за любую информацию или исправления.
Это ошибки времени выполнения. Они не могут быть результатом аннотаций типов.