基本的な型
const name: string = "Alice";
const age: number = 25;
const isActive: boolean = true;
const id: bigint = 100n;
const symbol: symbol = Symbol("id");
const numbers: number[] = [1, 2, 3];
const names: Array<string> = ["Alice", "Bob"];
const tuple: [string, number] = ["Alice", 25];
const namedTuple: [name: string, age: number] = ["Alice", 25];
const user: { name: string; age: number } = { name: "Alice", age: 25 };
let anyValue: any = "anything";
let unknownValue: unknown = "must check type";
function throwError(): never {
throw new Error("error");
}
型エイリアスとインターフェース
type User = {
id: string;
name: string;
email: string;
};
type ID = string | number;
interface Product {
id: string;
name: string;
price: number;
}
interface AdminUser extends User {
role: "admin";
permissions: string[];
}
type ExtendedProduct = Product & {
category: string;
};
ユニオン型とインターセクション型
type Status = "pending" | "approved" | "rejected";
type StringOrNumber = string | number;
type Employee = User & { department: string };
type Result<T> =
| { success: true; data: T }
| { success: false; error: string };
function handleResult(result: Result<string>) {
if (result.success) {
console.log(result.data);
} else {
console.log(result.error);
}
}
ジェネリクス
function identity<T>(value: T): T {
return value;
}
function pair<T, U>(first: T, second: U): [T, U] {
return [first, second];
}
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
interface ApiResponse<T> {
data: T;
status: number;
message: string;
}
class Container<T> {
private value: T;
constructor(value: T) {
this.value = value;
}
getValue(): T {
return this.value;
}
}
ユーティリティ型
interface User {
id: string;
name: string;
email: string;
age?: number;
}
type PartialUser = Partial<User>;
type RequiredUser = Required<User>;
type ReadonlyUser = Readonly<User>;
type UserName = Pick<User, "id" | "name">;
type UserWithoutEmail = Omit<User, "email">;
type UserRecord = Record<string, User>;
type Status = "pending" | "approved" | "rejected";
type ActiveStatus = Exclude<Status, "rejected">;
type ExtractedStatus = Extract<Status, "pending" | "approved">;
type NonNullableString = NonNullable<string | null | undefined>;
function getUser() {
return { id: "1", name: "Alice" };
}
type UserReturn = ReturnType<typeof getUser>;
type GetUserParams = Parameters<typeof getUser>;
型ガード
function process(value: string | number) {
if (typeof value === "string") {
return value.toUpperCase();
}
return value * 2;
}
function handleError(error: Error | string) {
if (error instanceof Error) {
return error.message;
}
return error;
}
interface Dog {
bark(): void;
}
interface Cat {
meow(): void;
}
function speak(animal: Dog | Cat) {
if ("bark" in animal) {
animal.bark();
} else {
animal.meow();
}
}
function isUser(value: unknown): value is User {
return (
typeof value === "object" &&
value !== null &&
"id" in value &&
"name" in value
);
}
条件型
type IsString<T> = T extends string ? true : false;
type UnwrapPromise<T> = T extends Promise<infer U> ? U : T;
type Result = UnwrapPromise<Promise<string>>;
type ArrayElement<T> = T extends (infer U)[] ? U : never;
type Item = ArrayElement<string[]>;
type ReturnOf<T> = T extends (...args: any[]) => infer R ? R : never;
Mapped Types
type Nullable<T> = {
[K in keyof T]: T[K] | null;
};
type Mutable<T> = {
-readonly [K in keyof T]: T[K];
};
type OptionalToRequired<T> = {
[K in keyof T]-?: T[K];
};
type Getters<T> = {
[K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};
type UserGetters = Getters<User>;
テンプレートリテラル型
type HttpMethod = "GET" | "POST" | "PUT" | "DELETE";
type Endpoint = "/users" | "/products";
type ApiRoute = `${HttpMethod} ${Endpoint}`;
type UpperCase = Uppercase<"hello">;
type LowerCase = Lowercase<"HELLO">;
type Capitalize = Capitalize<"hello">;
type Uncapitalize = Uncapitalize<"Hello">;
よくあるパターン
type Nullable<T> = T | null;
type Optional<T> = T | undefined;
type Maybe<T> = T | null | undefined;
type Result<T, E = Error> =
| { ok: true; value: T }
| { ok: false; error: E };
type DeepPartial<T> = {
[K in keyof T]?: T[K] extends object ? DeepPartial<T[K]> : T[K];
};
type ReadonlyArray<T> = readonly T[];
type AsyncReturnType<T extends (...args: any) => Promise<any>> =
T extends (...args: any) => Promise<infer R> ? R : never;
実用Tips
const colors = ["red", "green", "blue"] as const;
type Color = typeof colors[number];
const config = {
port: 3000,
host: "localhost",
} satisfies Record<string, string | number>;
const statusMap = {
pending: "保留中",
approved: "承認済み",
rejected: "拒否",
} as const;
type Status = keyof typeof statusMap;
関連記事
← 一覧に戻る