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の様々な型注釈

Last updated at Posted at 2024-08-13

アジェンダ

TypeScriptには、さまざまな型があります。この記事では、これらの型の概要を簡単にまとめます。これらの型を理解することで、より堅牢で安全なコードを書くことができます。

様々な型の概要

リテラル型

リテラル型は、特定の値のみを許容する型です。これは、値の制約を強化するために使用されます。

type Direction = 'North' | 'South' | 'East' | 'West';

上記の例では、Direction型は'North', 'South', 'East', 'West'のいずれかの文字列のみを取ることができます。

プリミティブ型

プリミティブ型は、基本的なデータ型であり、イミュータブルな性質を持ちます。これらの型には、stringnumberbooleanなどがあります。

type PrimitiveString = string;
type PrimitiveNumber = number;

プリミティブ型は、単純でありながら、JavaScriptの基本的な型システムの中心を成しています。

オブジェクトの型注釈

オブジェクト型は、複雑なデータ構造を扱う型です。オブジェクト型注釈を使用することで、オブジェクトの構造を明確に定義できます。

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

上記の例では、User型は、id, name, ageのプロパティを持つオブジェクトを表しています。

配列の型注釈

配列の型注釈は、配列内の要素の型を定義します。これにより、配列が持つべき要素の型を明確にできます。

type NumberArray = number[];

この例では、NumberArray型は、number型の要素のみを含む配列を表します。

ユニオン型

ユニオン型は、複数の型を組み合わせて、一つの型として扱うことができます。これは、変数が複数の型を取る可能性がある場合に使用されます。

type ID = string | number;

この例では、ID型は、string型またはnumber型の値を取ることができます。

インターセクション型

インターセクション型は、複数の型を組み合わせて、一つの型に統合することができます。これは、複数の型のプロパティを持つオブジェクトを定義する際に便利です。

type Nameable = {
  name: string;
};

type Ageable = {
  age: number;
};

type Person = Nameable & Ageable;

上記の例では、Person型は、nameageの両方のプロパティを持つオブジェクトを表しています。

型エイリアス

型エイリアスは、複雑な型定義に名前を付けて再利用しやすくするためのものです。型エイリアスを使うことで、コードの可読性が向上します。

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

型エイリアスは、プリミティブ型やオブジェクト型など、どんな型でも定義することができます。

型アサーション

型アサーションは、TypeScriptに対して「この値は特定の型である」と明示的に示す方法です。これは、コンパイラが型を誤解する可能性がある場合に有効です。

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

この例では、someValueunknown型であるにもかかわらず、string型として扱うことができ、その結果lengthプロパティにアクセスできます。

参考

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