「Reactに入門した人のためのもっとReactが楽しくなるステップアップコース完全版」を学習したのでまとめる
TypeScript
TypeScriptとは、Microsoftが開発したオープンソースの言語
JavaScriptに「型」という概念
より安全にバグが少なく開発できる
開発者間で認識を合わせやすい
エディタでコード補完も聞くので開発効率が良い
コンポーネント指向のReactと非常に相性が良い
「.ts」、「.tsx」の拡張子で表現される
基本的な型
sample.tsx
/**eslint-disable @typescript-eslint/no-unused-vars */
/** typeScriptの基本の型 */
//boolean
let bool: boolean = true;
//number 数値
let num: number = 0;
//string 文字
let str: string = "A";
//Array 配列
let arr1: Array<number> = [0, 1, 2];
let arr2: number[] = [0, 1, 2];
//tuple
let tuple: [number, string] = [0, "A"];
//any
let any1: any = false;
//void
const fancA = (): void => {
const test = "TEST";
}
//null
let null: null = null;
//undefined
let undefined1: undefined
//object
let obj1: object = {};
let obj2 { id: number, name: string } = {id: 0, name: "AAA"};
引数の型指定
sample.tsx
export const Practice1 = () => {
const calTotalFee = (num: number) => { //引数の型指定(num: number)
const total = num * 1.1;
console.log(total);
};
const onclickPractice = () => calTotalFee("1000");
return (
<div>
<p>引数の型指定</p>
<button onClick={onclickPractice}>実行</button>
</div>
);
};
返却値の指定
sample.tsx
export const Practice2 = () => {
const getTotalFee = (num: number): number => {
const total = num * 1.1;
return total; //返却値の指定
};
const onclickPractice = () => {
console.log(getTotalFee(1000));
};
return (
<div>
<p>返却値の型指定</p>
<button onClick={onclickPractice}>実行</button>
</div>
);
};
変数の指定
sample.tsx
export const Practice3 = () => {
const getTotalFee = (num: number): number => {
const total = num * 1.1;
return total;
};
const onclickPractice = () => {
let total: number = 0; //変数の指定
total = getTotalFee(1000);
console.log(total);
};
return (
<div>
<p>変数の型指定</p>
<button onClick={onclickPractice}>実行</button>
</div>
);
};
propsの型定義
todo.ts
export type TodoType = { //型定義
userId: number;
id: number;
title: string;
completed: boolean;
};
Todo.tsx
import { TodoType } from "./types/todo"; //型のインポート
export const Todo = (
props: Pick<TodoType, "userId" | "title" | "completed">
//Pick<TodoType, TからKeysに指定したキーだけを含むオブジェクトの型を返す
//Omit<T, Keys>, TからKeysで指定したプロパティを除いたobject型を返す
) => {
const { title, userId, completed } = props;
const completeMark = completed ? "[完]" : "[未]";
return <p>{`${completeMark} ${title}(ユーザー:${userId})`}</p>;
};
コンポーネント自体の型定義
MyComponenProps.tsx
type MyComponenProps = {
children: React.ReactNode;
};
const MyComponent: FC<MyComponenProps> = (props) => {
return (
<div>{props.children}</div>
);
};
ライブラリの型定義
define.ts
react-router-dom //ライブラリ
@types/react-router-dom //ライブラリの型
ライブラリの型定義は、開発元から探す。
例)axiosのライブラリの型定義を確認したい
1.axiosライブラリのgithubへ移動する。
2.github上で「index.d.ts」を探す
3.2番が無ければ、github上のpackege.jsonの中の"typing"の項目があり、そこに記載がある場合がある。
開発環境コマンド
開発環境では、下記コマンドでreact-typescriptを実施
app
$ npx create-react-app my-app --template typescript
my-app部分は、実際のアプリ名