Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
1
Help us understand the problem. What is going on with this article?
@10mi8o

TypeScriptの基本的な型指定をメモ

絶賛、TypeScriptをキャッチアップ中。
型指定で、どうやって書くっけ...?みたいな型指定があるんで、忘備録的にメモ。

配列の型指定

複数の型を使いたいときはunion型を利用

const instruments: string[] = ["Guitar", "Base", "Drums"];
const mix: (number | string)[] = ["hoge", 12, "fuga"];

リテラル型

決まった値のみしか受け入れない。
constで宣言すると型推論はリテラル型になる。

以下の型推論は同じリテラル型となる。
const guitar: "guitar" = "guitar";
const guitar = "guitar";

letで宣言すると、以下の場合は、string型になる。

let guitar = "guitar"

使用場面として、union型を併用すると、enum型と同じような使い方ができる。
基本的には、enum型のほうが分かりやすいと思う。

enumのように使える
let clothSize: "large" | "meduim" | "small" = "small";

enum型

enum Size {
  SHORT = "SHORT",
  MEDIUM = "MEDIUM",
  LARGE = "LARGE",
}

const coffee = {
  hot: true,
  size: Size.SHORT,
};

typeエイリアス

型を変数みたいに扱えるようにする。

type ClothSize = "small" | "medium" | "large";
let clothSize: ClothSize = "small";

関数に型をつける

//関数に型をつける
function add(num1: number, num2: number): number {
  return num1 + num2;
}

//型注釈
const anotherAdd: (n1: number, n2: number) => number = add;

//アロー関数
const doubleNum: (num: number) => number = (num) => num * 2;

//コールバック関数
function doubleAndHandle(num: number, cb: (num: number) => number): void {
  const doubleNum = cb(num * 2);
  console.log(doubleNum);
}

doubleAndHandle(21, (doubleNum) => {
  return doubleNum;
});
1
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
10mi8o
もふもふした動物と音楽が好き。

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
1
Help us understand the problem. What is going on with this article?