0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

個人的備忘録:React初心者がJavaScriptからTypeScriptに切り替える際につまずいた構文の違いまとめ

Posted at

はじめに

この記事では、Next.js を使って開発を進める中で、TypeScript(TS)と JavaScript(JS)の構文の違いについて整理します。

個人の備忘録程度の走り書きとなっておりますが、温かい目で見守っていただければ幸いです。

日々の開発で混乱しないよう、基本的な構文の違いをまとめておきます。

書こうと思ったきっかけ

受講しているITスクールのハッカソンの開発の一環で、Next.js プロジェクト内で JavaScript と TypeScript の書き方が混在していたため、型の指定や構文の違いで戸惑う場面がありました。今後の開発でスムーズに書き分けるためにも、備忘録として記事にまとめています。

内容

1. 変数や関数の型定義

JavaScript(型なし)

const userName = "Taro";
function greet(name) {
  return "Hello, " + name;
}

TypeScript(型あり)

const userName: string = "Taro";
function greet(name: string): string {
  return "Hello, " + name;
}

2. オブジェクトの型定義

JavaScript

const user = {
  name: "Taro",
  age: 25
};

TypeScript

type User = {
  name: string;
  age: number;
};

const user: User = {
  name: "Taro",
  age: 25
};

3. useStateの型指定(React)

JavaScript

const [count, setCount] = useState(0);

TypeScript

const [count, setCount] = useState<number>(0);

4. propsの型定義

JavaScript

function Hello(props) {
  return <h1>Hello, {props.name}</h1>;
}

TypeScript

type HelloProps = {
  name: string;
};

function Hello({ name }: HelloProps) {
  return <h1>Hello, {name}</h1>;
}

5. Next.js API Routeの型定義

JavaScript

export default function handler(req, res) {
  res.status(200).json({ message: "Hello World" });
}

TypeScript

import type { NextApiRequest, NextApiResponse } from "next";

export default function handler(req: NextApiRequest, res: NextApiResponse) {
  res.status(200).json({ message: "Hello World" });
}

まとめ

Next.js では .tsx という拡張子を使えば、Reactコンポーネントに TypeScript を導入できます。型安全にコードを書きたいときや、補完機能を強化したいときには TypeScript が非常に便利だと感じました...!

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?