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 2026-01-17

2026/01/18現在。React本のTypeScript節を読書中なので順次追記します!

変数の型指定

変数宣言の書き方はこう

const 変数/定数名: 型名 = 初期値;

型名は次に記載する種類がある

論理型

const flag: boolean = false;

数値型

const num: number = 3;

文字列型

const title: string = `文字列型`;

配列型

const books: string[] = [`タイトル`, `たいとる` ,`title`];

タプル型

const person: [string, number, boolean] = [`名前`, 4, false];

配列であるが、要素ごとの型を定義する

連想配列型

const addresses: {[index: string] : string;} = {
  'キー1': '値1',
  'きー2': 'あたい2',
}

オブジェクト型

const member: {
  name: string,
  age: number,
  married?: boolean
} = {
  name: 'なまえ',
  age: 10,
  married: true
}

member.nameはstringの要領で型を決められる
末尾に?があるものは省略可能↓

const member: {
  name: string,
  age: number,
  married?: boolean
} = {
  name: 'なまえ',
  age: 10,
}

any型

何でもいい。(当たり前だけど非推奨)
例えばこのようなこともできる

let age: any;

age = 10;
age = '年齢';
age = true;

unknown型

何でもいい。が、any型とは違い、「不明」であることを表す。
型チェックをしないとメソッド実行ができない

let age: unknown;

age = 10;
age = '年齢';

// 下記でエラーになる
console.log(age.substring(1));

age = true;
// 型チェックが必要
if (typeof age === 'string') {
  console.log(age.substring(1));
}

ユニオン型

任意のどれかの型であることを表す「|」で書く

let age: string | number;
age = '年齢';
age = 30;

配列でもOK

let list: (string | number)[] = ['例えば氏名', 10, '住所とか'];

nullを指定することも可能らしい

let age: string | number | null;
age = '年齢';
age = 30;

型エイリアス

オブジェクト型を何度も書くのは面倒くさい。
別名で定義を残しておくイメージ

type Aaa = {
  name: string,
  age: number,
  address: string
};
// Aaaという型を定義した

let b: Aaa = {
  name: '名前',
  age: 10,
  address: '地球'
}
// 変数bの型はAaa。オブジェクト型にみえるけど、再利用が可能。

戻り値の型指定

void型

関数の戻り値が無いことを表す

function abc(name: string): void {
  console.log();
}

never型

用途が分かっていない。
・関数が常に例外を発生する
・無限ループである
など関数を終端まで実施できないことを表すらしい

function abc(name: string): never {
  throw new Error('Error');
}
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?