【U】最速で学ぶTypeScript

6: TypeScriptのデータ型

// リテラル型 文字列リテラル
// const name: "hello";
const name = "hello";

// 明示的にデータの形を指定 → 『アノテーション』
let username: string = "Hello";
let num: number = 2;
let bool: boolean = true;


// オブジェクトの形の定義
interface NAME {
    first: string;
    last: string;
};

let nameObj: NAME = { first: "Yamada", last: "Taro" };

--------------------------------------------------------------------------
// 「?」を付けることである場合のみ指定、なくてもOK
interface NAME {
    first: string;
    last?: string; 
};

// 「null型」も指定
interface NAME {
    first: string;
    last?: string || null; 
};
--------------------------------------------------------------------------


// 関数の形の定義
// 推論
const func1 = ( x: number, y: number ) => {
    return x + y;
};
// 明示的に指定
const func1 = ( x: number, y: number ): number => {
    return x + y;
};


7: Intersection Types

複数のタイプを結合する処理

type PROFILE = {
    age: number;
    city: string;
};
type LOGIN = {
    username: string;
    password: string;
};

// 結合!!!!
type USER = PROFILE & LOGIN;

const userA: USER = {
    age: 30;
    city: "Tokyo";
    username: "xxx";
    password: "yyy";
}


8: Union Types

変数が受け取れるデータが正しい値を制限することができる

let value: boolean | number;
value = true; 〇
value = "hello"; ×

// 配列の要素に使用
let arrayUni: (number | string)[];
arrayUni = [0, 1, 2 "hellow"]; 〇
arrayUni = [0, 1, 2 "hellow", true]; ×


9: Literal Types

// リテラルとユニオンの組み合わせ
//文字列リテラルにユニオンタイプを使用
let company: "Facebook" | "Google" | "Amazon";
company = "Facebook"; 〇
company = "Apple"; ×

// 数値(数字リテラル?)に使用
let memory = 256 | 512;
memory = 256 ; 〇
memory = 12; ×


10: typeof

宣言済み変数の型を取得する
ex) 人物のデータタイプなど
constで定義されているjsonの構造が複雑な時にtypeofを使用することで全て継承してくれる

// 宣言済みの変数
let msg: string = "Hi";

// msgの方を取得して型を定義(継承している)
let msg2: typeof msg;
msg2 = "hello"; 〇
msg2 = 2; ×


// オブジェクトに適用
let animal = { cat: "small cat" }; //  = string(推論)
let newAnimal: typeof animal = { cat: "big cat" }; //  = string(推論)


11: keyof

type KEYS = {
    primary: string;
    secondary: string;
};
// KEYSの内容をユニオンタイプで取り出してくれる
let key typeof KEYS;
key = "primary"; 〇
key = "others;" ×


// typeof + keyof
// typeof : 型の継承
// keyof : ユニオンタイプで取り出す
const SPORTS = {
    soccer: "Soccer",
    baseball: "Baseball",
};
let keySports: keyof typeof SPORTS;
keySports = "Soccer"; 〇
keySports = "Soccer..."; ×


12: enum(列挙型)

c言語に近い
自動に連番を付けてくれる機能
ex) パソコンを管理するシステム
1台1台にIDとOSのタイプを登録する必要がある

enum OS {
     Windows, // OS.Windows = 0
     Mac, // OS.Mac= 1
     Linux, // OS.Linux= 2
};
interface PC {
    id: number;
    OSType: OS;
};

const PC1: PC = {
    id: 1,
    OSType: OS.Windows, // OS.Windows = 0
};
const PC2: PC = {
    id: 2,
    OSType: OS.Mac, // OS.Mac= 1
};


13: 型の互換性

const comp1 = "test"; // comp1: "test" (推論)
let comp2: string = comp1; // 抽象的→具体的 は代入することができる!!

// 反対
let comp3: string = "test";
let comp4: "test" = comp3; ×


// 関数の互換性
let funcComp1 = (x: number) => {};
let funcComp2 = (x: string) => {};

funcComp1 = funcComp2; ×
funcComp2 = funcComp1; ×


14: Generics(ジェネリックス)

reactの「props」の型を指定

interface GEN<T> {
    item: T;
}
const gen0: GEN<string> = { item: "hello" }; 〇
const gen1: GEN = { item: "hello" }; ×
const gen2: GEN<number> = { item: "hello" }; ×

// デフォルトの設定
interface GEN1<T = string> {
    item: T;
}
const gen3: GEN1 = { item: "hello" }; 〇

// 指定できるデータタイプを制限 extends
interface GEN2<T extends string | number> {
    item: T;
}
const gen4: GEN2<string> = { item: "hello" }; 〇
const gen5: GEN2<number> = { item: 12 }; 〇
const gen6: GEN2<boolean> = { item: true }; ×

// 関数に対する generics
function funcGen<T>(props: T) {
    return { item: props }
};
const gen7 = funcGen<string>("test"); 〇
const gen8 = funcGen("test"); 〇
const gen9 = funcGen<string | null>(null); 〇

// 関数に対する extends
function funcGen1<T extends string | null>(props: T) {
    return { value: props }
};
const gen10 = funcGen1("hello"); 〇
const gen12 = funcGen1(111); ×

// props の使い方
interface Props {
    price: number;
};
function funcGen3<T extends Props>(props: T) {
    return { value: props.proce}
};
const gen13 = funcGen3({price: 10});

// アロー関数での記述
const funcGen4 = <T extends Props>(props: T) => {
    return { value: props.proce}
};

 

15: JSON型推論

typeof を JSON のデータに適用

// data.json
[
  {
    "id": 1,
    "name": "Leanne Graham",
    "username": "Bret",
    "email": "Sincere@april.biz",
    "address": {
      "street": "Kulas Light",
      "suite": "Apt. 556",
      "city": "Gwenborough",
      "zipcode": "92998-3874",
      "geo": {
        "lat": "-37.3159",
        "lng": "81.1496"
      }
    },
    "phone": "1-770-736-8031 x56442",
    "website": "hildegard.org",
    "company": {
      "name": "Romaguera-Crona",
      "catchPhrase": "Multi-layered client-server neural-net",
      "bs": "harness real-time e-markets"
    }
  },
  {
    "id": 2,
    "name": "Ervin Howell",
    "username": "Antonette",
    "email": "Shanna@melissa.tv",
    "address": {
      "street": "Victor Plains",
      "suite": "Suite 879",
      "city": "Wisokyburgh",
      "zipcode": "90566-7771",
      "geo": {
        "lat": "-43.9509",
        "lng": "-34.4618"
      }
    },
    "phone": "010-692-6593 x09125",
    "website": "anastasia.net",
    "company": {
      "name": "Deckow-Crist",
      "catchPhrase": "Proactive didactic contingency",
      "bs": "synergize scalable supply-chains"
    }
  },
...
  {
    "id": 10,
    "name": "Clementina DuBuque",
    "username": "Moriah.Stanton",
    "email": "Rey.Padberg@karina.biz",
    "address": {
      "street": "Kattie Turnpike",
      "suite": "Suite 198",
      "city": "Lebsackbury",
      "zipcode": "31428-2261",
      "geo": {
        "lat": "-38.2386",
        "lng": "57.2232"
      }
    },
    "phone": "024-648-3804",
    "website": "ambrose.net",
    "company": {
      "name": "Hoeger LLC",
      "catchPhrase": "Centralized empowering task-force",
      "bs": "target end-to-end models"
    }
  }
]
// App.tsx
import Data from "./data.json"

typeof USERS = typeof Data;
⇒ 推論で定義してくれる!!


16: React Hooks Props型

v 16.8 からReact Hooks が搭載
クラスコンポーネント ➡ ファンクショナルコンポーネント をベースに開発

// App.tsx
const App: React.FC = () => {
    return (
        <div className="App">
            <header className="App-header">
                <TestComponent text="hello from App" /> 〇
                <TestComponent text1="hello from App" /> ×
                <TestComponent text={123} /> ×
            </header>
        </div>
    );
}
// TestComponent.tsx
import React from 'react';

interface Props = {
    text: string
};

const TestComponent: React.FC<Props> = (props) => {
    return(
        <div><h1>{props.text}</h1></div>
    );
}

export defailt TestComponent;


16: React Hooks useState

// TestComponent.tsx
import React, { useState } from 'react';

const TestComponent: React.FC<Props> = (props) => {
    const [count, setCount] = useState(0); // 自動でnumber型にしてくれる
    const [countFlg, setCountFlg] = useState(true); // 自動でboolean型にしてくれる
    return(
        <div><p>{count}</h1></p>
    );
}

export defailt TestComponent;

この記事が気に入ったらサポートをしてみませんか?