1
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 学習メモ

Posted at

TypeScript 学習メモ

基本のプリミティブ型たち

boolean

let isDone: boolean = true;

number

let age: number = 25;

string

let name: string = "Maeda";

array 型(配列)

let scores: number[] = [10, 20, 30];

tuple 型(要素の型と順番がガチ固定)

let user: [number, string] = [1, "Haruka"];

any 型(なんでも入るけど危険)

let data: any = 100;
data = "hello"; // 余裕で通る

とりあえず一旦なんでも通すため、なるべく避ける意識大事


unknown 型(安全な any)

let input: unknown = "hi";
if (typeof input === "string") {
  console.log(input.toUpperCase());
}

void 型(返り値なし)

function greet(): void {
  console.log("hello");
}

null / undefined 型

let n: null = null;
let u: undefined = undefined;

never 型(絶対戻らない)

function error(msg: string): never {
  throw new Error(msg);
}

object 型

let person: object = { name: "Maeda" };

Type Aliases / interface まわり

Type Alias(型に名前つける)

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

interface(型の設計図)

interface Product {
  id: number;
  price: number;
}

応用の型

Union 型(A または B)

let value: string | number = 10;

Intersection 型(合体)

type A = { id: number };
type B = { name: string };
type AB = A & B; // 両方必須

Literal 型(値そのものを型に)

let status: "active" | "inactive";

enum 型(名前付き定数)

enum Role {
  Admin,
  User,
  Guest,
}

型安全

「型が違うことをしたらコンパイルで止める」っていう TS の最大の武器
JS みたいに実行してからエラーではなく、先にエラーを出してくれる優しい世界

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