← 講座に戻る: TypeScript from scratch

TypeScript with the DOM and fetch

動画は近日公開

Until now you have written code that lives only in the terminal. In the last week we take it to the real world: web pages and data coming from servers. TypeScript knows the browser DOM through its built-in type definitions, which are enabled with the lib: ["DOM"] option in tsconfig. In this lesson you learn to manipulate elements with type safety and to request data with fetch, and you will see that the biggest risk of TypeScript appears right at that boundary with the outside world.

Selecting elements

document.querySelector returns Element | null: the element may not exist (null) and, in general, it is a generic Element with no specific properties such as value. With strict you must handle both cases. You can pass a generic, querySelector<HTMLInputElement>('#name'), to state the expected type, but it is still an assertion from you, not a check. Safer is to use instanceof, which really checks the type at runtime and narrows at the same time. For events, addEventListener infers the event type from its name: a 'click' receives a MouseEvent.

typescript
// tsconfig needs: "lib": ["ES2023", "DOM"]
function getInput(selector: string): HTMLInputElement {
  const element = document.querySelector(selector);
  if (!(element instanceof HTMLInputElement)) {
    throw new Error('Input not found: ' + selector);
  }
  return element;
}

const nameInput = getInput('#name');
const button = document.querySelector('button');
const output = document.querySelector('#output');

button?.addEventListener('click', (event: MouseEvent) => {
  if (output) {
    output.textContent = 'Hello, ' + nameInput.value + ' (x=' + event.clientX + ')';
  }
});

fetch and the any problem

fetch returns a promise of Response, and response.json() returns a promise of any. That any is the door through which unchecked data enters your program. If you write const user: User = await response.json(), the compiler accepts it, but there is no guarantee: the server may have changed, be down or return something else. Types are erased when compiling, so nothing protects you at runtime. That is why it is good practice to treat the result as unknown and validate it, the topic of the next lesson. Here we first see the basic pattern, with the return type of the async function as Promise<T> and the response.ok check.

typescript
interface Todo {
  id: number;
  title: string;
  completed: boolean;
}

async function fetchTodo(id: number): Promise<Todo> {
  const response = await fetch('https://jsonplaceholder.typicode.com/todos/' + id);
  if (!response.ok) {
    throw new Error('HTTP error ' + response.status);
  }
  const data: unknown = await response.json();
  return data as Todo; // assertion: we trust the server (see next lesson to validate)
}

fetchTodo(1)
  .then((todo) => console.log(todo.title))
  .catch((error: unknown) => {
    console.error(error instanceof Error ? error.message : error);
  });

A type assertion, written with as, tells the compiler: trust me, I know more than you. It is a legitimate tool in specific cases, but every as is an unverified promise. A good rule is to count them: if your project has many, validation is probably missing. And avoid the double assertion as unknown as T, which silences the compiler completely.

✎ マイノート

このブラウザにのみ保存されます。ログインするとアカウントに保存できます。0/5000 文字

← 前へ次へ →