1
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?

TypeScriptの基本文法と書き方(型定義以外)

Last updated at Posted at 2024-07-30

TypeScriptの基本文法

変数宣言

TypeScriptでは、letconst、およびvarを使用して変数を宣言します。constは再代入不可、letは再代入可能、varはスコープが関数スコープです。

typescript
let mutableVariable: number = 10;
const immutableVariable: string = "Hello";
var functionScopedVariable: boolean = true;

配列

配列の型は、要素の型の後に [] を付けるか、Array<型> を使用します。

typescript
const numbers: number[] = [1, 2, 3];
const strings: Array<string> = ["a", "b", "c"];

タプル

タプルは固定長の配列で、各要素に異なる型を持たせることができます。

typescript
const tuple: [string, number] = ["Alice", 30];

オブジェクト

オブジェクトの型は、プロパティ名とその型を指定します。

typescript
const person: { name: string; age: number } = {
    name: "Alice",
    age: 30,
};

関数宣言

関数の宣言方法には、関数宣言、関数式、アロー関数があります。

typescript
// 関数宣言
function add(a: number, b: number): number {
    return a + b;
}
// 関数式
const subtract = function(a: number, b: number): number {
    return a - b;
};
// アロー関数
const multiply = (a: number, b: number): number => a b;

デフォルトパラメータ

関数の引数にデフォルト値を設定できます。

typescript
function greet(name: string = "Guest"): string {
    return Hello, ${name};
}

オプショナルパラメータ

関数の引数をオプショナルにすることができます。

typescript
function log(message: string, userId?: string): void {
    console.log(message, userId || "Not signed in");
}

スプレッド構文とレストパラメータ

スプレッド構文は配列やオブジェクトを展開するために使用され、レストパラメータは可変長引数を受け取るために使用されます。

typescript
// スプレッド構文
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5];
const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 };
// レストパラメータ
function sum(...numbers: number[]): number {
    return numbers.reduce((acc, curr) => acc + curr, 0);
}

クラス

TypeScriptでは、クラスを使用してオブジェクト指向プログラミングを行います。

typescript
class Person {
  name: string;
  age: number;

  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }

  greet(): string {
    return `Hello, my name is ${this.name}`;
  }
}

const person = new Person("Alice", 30);

継承

クラスは他のクラスを継承することができます。

typescript
class Employee extends Person {
  employeeId: number;

  constructor(name: string, age: number, employeeId: number) {
    super(name, age);
    this.employeeId = employeeId;
  }

  getDetails(): string {
    return `${this.name}, ${this.age} years old, Employee ID: ${this.employeeId}`;
  }
}

const employee = new Employee("Bob", 25, 12345);

非同期処理

TypeScriptでは、async/awaitを使用して非同期処理を行います。

typescript
async function fetchData(url: string): Promise<any> {
  const response = await fetch(url);
  const data = await response.json();
  return data;
}

モジュール

TypeScriptでは、importexportを使用してモジュールを管理します。

typescript
// モジュールのエクスポート
export const pi = 3.14;
export function calculateCircumference(diameter: number): number {
  return diameter pi;
}
// モジュールのインポート
import { pi, calculateCircumference } from './math';
console.log(calculateCircumference(10));

名前付きエクスポートとデフォルトエクスポート

モジュールは名前付きエクスポートとデフォルトエクスポートの両方をサポートします。

typescript
// 名前付きエクスポート
export const name = "Alice";
export function greet(): void {
console.log("Hello");
}
// デフォルトエクスポート
const defaultExport = "Default Export";
export default defaultExport;
// インポート
import defaultExport, { name, greet } from './module';

型アサーション

型アサーションは、ある型を別の型として扱うことを示します。

typescript
let someValue: unknown = "this is a string";
let strLength: number = (someValue as string).length;

非nullアサーション演算子

非nullアサーション演算子(!)は、値がnullまたはundefinedでないことを示します。

typescript
let someValue: string | null = "Hello";
console.log(someValue!.length); // someValueがnullでないことを保証

オプショナルチェイニング

オプショナルチェイニング(?)は、プロパティが存在しない場合にundefinedを返します。

typescript
let user: { name?: string } = {};
console.log(user.name?.toUpperCase()); // undefined

null合体演算子

null合体演算子(??)は、nullまたはundefinedの場合にデフォルト値を返します。

typescript
let input: string | null = null;
let defaultValue = input ?? "default";
console.log(defaultValue); // "default"
1
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
1
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?