0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

TypeScript入門 — JavaエンジニアがTypeScriptを学ぶ理由

0
Posted at

TypeScript入門 — JavaエンジニアがTypeScriptを学ぶ理由

はじめに

TypeScriptはMicrosoftが開発した、JavaScriptに型を追加した言語です。

Javaエンジニアには「型がある」という概念が既に馴染んでいるため、JavaScriptよりTypeScriptの方が学びやすいという人が多いです。


JavaScriptとTypeScriptの違い

// JavaScript(型なし)
function greet(name) {
  return "Hello, " + name;
}
greet(123); // 数値を渡してもエラーにならない
// TypeScript(型あり)
function greet(name: string): string {
  return "Hello, " + name;
}
greet(123); // コンパイルエラー: 'number' は 'string' に割り当てられません

基本の型

// プリミティブ型
const name: string = "田中";
const age: number = 25;
const isActive: boolean = true;

// 配列
const scores: number[] = [80, 90, 70];

// オブジェクト型(インターフェース)
interface User {
  id: number;
  name: string;
  email: string;
}

const user: User = {
  id: 1,
  name: "田中",
  email: "tanaka@example.com"
};

JavaのクラスとTypeScriptの比較

// Java
public class User {
    private int id;
    private String name;

    public User(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public String getName() { return name; }
}
// TypeScript
class User {
  constructor(
    private id: number,
    private name: string
  ) {}

  getName(): string {
    return this.name;
  }
}

Javaのクラス構文とほぼ同じ感覚で書けます。


型エイリアスとユニオン型

// ユニオン型(Javaにないが直感的)
type Status = "active" | "inactive" | "pending";

const userStatus: Status = "active";
// const userStatus: Status = "deleted"; // エラー

// オプショナルプロパティ
interface Product {
  id: number;
  name: string;
  description?: string; // ?をつけるとundefined許容
}

Reactでの使い方

// Propsの型定義
interface CardProps {
  title: string;
  description: string;
  onClick: () => void;
}

export default function Card({ title, description, onClick }: CardProps) {
  return (
    <div onClick={onClick}>
      <h2>{title}</h2>
      <p>{description}</p>
    </div>
  );
}

型を定義することで、Props渡しのミスをエディタ上で即座に検出できます。


まとめ — JavaとTypeScriptの対応表

Java TypeScript
String string
int / double number
boolean boolean
class User {} class User {}
interface User {} interface User {}
Optional<String> string | undefined

JavaエンジニアはTypeScriptの型システムをほぼそのまま読めます。「JavaScriptに型をつけた言語」と理解すれば、フロントエンドの学習コストが大幅に下がります。

0
0
1

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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?