6
5

More than 1 year has passed since last update.

TypeScriptチートシート1(基本)

Last updated at Posted at 2021-12-28

1:boolean,number,string

let aaa: boolean = true
let bbb: string = "string"
let ccc: number = 100
let ddd: number = 3.14
let eee: number = -1

2:型注釈と型推論

明示的に書かなくても、代入した型から推測してくれる

let aaa = true
let bbb = "string"
let ccc = 100

3:オブジェクトに型を付ける

const person: {
  name: string;
  age: number;
} = {
  name: "jack",
  age: 20,
};

4:配列

const fruits:string[] = ['apple','banana','grape']

5:Tuple型

厳しく型注釈
要素の数、各要素の型をきめる

const book:[string,number,boolean] = ['business',1500, false]

可変長(レストパラメーターにも使える)

const friends :[string, ...string[]] = ["masaki","nana","keisuke"]

6:enum

上から0、1、2となる

enum CoffeeSize {
    SHORT,
    TALL,
    GRANDE
}

const coffee = {
  hot: true,
  size: CoffeeSize.TALL,
};

7:any

なんでも入る
javaScriptの世界と同じ
あんまり使わない方がよい

8:Union型

複数の型を定義できる

let unionType: number | string = 10;
let unionTypes: (number | string)[] = [21, "hello"];

9:Literal型

この型以外入りません

const apple: 'apple' = 'apple'
let clothSize :'small'|'medium'|'large' = 'large'

10:typeエイリアス

型を変数に入れるイメージ

type ClothSize = 'small' | 'medium' | 'large'
let clothSize: ClothSize = 'large'

11:関数に型を付ける

戻り値は型推論されるが、引数はされない

function add(num1: number, num2: number): number {
  return num1 + num2;
}

12:戻り値void

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

13:関数型

関数を保持する変数に型を付ける

function add(num1: number, num2: number): number {
  return num1 + num2;
}

//anotherAddに型を付けて関数addを代入している
const anotherAdd: (n1: number, n2: number) => number = add;

関数のtype

type IsPositiveFunc = (num: number) => boolean
const isPositive: IsPositiveFunc = num => num >= 0;

14:callback関数

function doubleAndHandle(num: number, cb: (num: number) => void): void {
  const doubleNum = cb(num * 2);
  console.log(num * 2);
}

doubleAndHandle(21, (doubleNum) => {
  return doubleNum;
});

15:never

決して何も返さない

function error(message: string):never {
    throw new Error(message);
    // while (true) {

    // }
}

17:null undefined

・null 値が欠如している
・undefined 初期化されておらず値が割り振られていない
できるだけundefinedを使う

any unknown

・any どんな型でも許容する=全く安全ではない
・unknown どんな型になるのか不明

6
5
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
6
5