TypeScript:
2026年5月6日npm install typescript
npm install --save-dev @types/nodetsconfig.jsonの作成:
npx tsc --initjsファイルへのコンパイル:
// 単体ファイル
npx tsc test.ts
// 全部
npx tsc
// 型チェックのみ
npx tsc --noEmittypeとinterface
type User = {
id: number;
name: string;
email: string;
};
interface User {
id: number;
name: string;
email: string;
}interfaceはユニオン型などに対応できない。
type ID = string | number;配列の型
number型だけ持つ配列の例:
const arr: number[] = [213, 432, 4321];
const arr: Array<number> = [213, 432, 4321];ユニオン型:
const arr: (number | string)[] = [1, "43r", 4321, 4312, "rre"];number または string を持つ配列
タプル型:
const arr:[number , string] = [1 , "43r"]要素の型と場所(index)がわかっている場合
関数の型
// どちらでもよい
type Increment = (num: number) => number;
type Increment = {
(num: number): number;
};const inc: Increment = (num) => {
return num + 1;
};
inc(5);type Incrementは関数自体の型なので関数名の右に書く
関数に直接書く場合:
const inc = (num: number): number => {
return num + 1;
};():の右側は返り値の型
非同期処理の場合:
const getNumber = async (): Promise<number> => {
}: Promise<>
返り値が無い関数の場合:
const msg = (message: string): void => {
console.log(message);
};: void
関数の返り値の型: ReturnType
const getUser = () => {
return { id: 1, name: "Test User" };
};
type User = ReturnType<typeof getUser>;オブジェクトの型
const scores: Record<string, number> = {
name: 33,
}Record<キーの型, 値の型>
type Status = "idle" | "loading" | "error"
const messages: Record<Status, string> = {
idle: "待機中",
loading: "読み込み中",
error: "エラー"
}キーにUnion型を使うと相性が良い
type Theme = "light" | "dark";
type PlanKey = "FREE" | "PRO";
const badgeColors: Record<Theme, Record<PlanKey, string>> = {
light: {
FREE: "gray-200",
PRO: "blue-500",
},
dark: {
FREE: "gray-800",
PRO: "blue-400",
},
};型の継承
interface:extends
// interface
interface Person {
name: string;
age: number;
}
interface Employee extends Person {
jobTitle: string;
}type:&
// type
type Person = {
name: string;
age: number;
};
type Employee = Person & {
jobTitle: string;
};chidrenを含めた型
React.PropsWithChildren
type SectionWrapperProps = React.PropsWithChildren<SectionTitleProps>;
const SectionWrapper = ({
children,
sectionTitle,
titlePosition,
}: SectionWrapperProps) => {set関数の型
React.Dispatch<React.SetStateAction<number | null>>;export type SetStateType<T> = React.Dispatch<React.SetStateAction<T>>;
setActiveIndex: SetStateType<number | null>;
setNameTyped: SetStateType<string> 長い部分を
SetStateType<T>にして使い回す
propsで渡たされたオブジェクト
DBから取得したような多くの要素を含むオブジェクトをpropsで渡しても全ての要素を使うとは限らないので、どの要素を使っているか型で明示する。
*以下のOmitもPickもただの型定義なので要素を削るわけではない。
Omit
type User = {
id: string;
email: string;
password: string;
createdAt: Date;
role: boolean;
};type PublicUser = Omit<User, "password" | "role">;propsとして渡すときに親側でfilter関数等でpasswordとroleを削ったものを受け取るような場合
Pick
PickはOmitと違い「何を使うのか」明示する
type PublicUser = Pick<User, "id" | "email">;複数の要素を持つオブジェクトが渡されてもUIでは一部の要素しか使わないような場合
typescript
/other