サバイバルTypeScript
#TypeScript
https://typescriptbook.jp/
簡単な関数
code:increment.ts
function increment(num) {
return num + 1;
}
console.log(increment(999));
この時点ではまだJavaScript。これを実行してみる。
code:sh
$ deno run increment.ts
1000
タイプチェックを行ってみる。
code:sh
$ deno check increment.ts
Check file:///Users/thata/src/survival-ts/increment.ts
error: TS7006 ERROR: Parameter 'num' implicitly has an 'any' type.
function increment(num) {
~~~
at file:///Users/thata/src/survival-ts/increment.ts:1:20
numパラメータが any 型だと怒られるので型注釈を入れてみる。
code:diff
diff --git a/increment.ts b/increment.ts
index aaa66ea..a342031 100644
--- a/increment.ts
+++ b/increment.ts
@@ -1,4 +1,4 @@
-function increment(num) {
+function increment(num: number) {
return num + 1;
}
型注釈を入れたら再度タイプチェックをを行ってみる → 今度はOK
code:sh
$ deno check increment.ts && echo ok
ok
denoでのTypeScriptの型チェック方法
code:sh
USAGE:
deno check OPTIONS <file>...
Reactでいいねボタンを作ろう
プロジェクトを作成
code:sh
cd ~/src
npx create-react-app like-button --template typescript
cd like-button
npm start
code:diff
diff --git a/src/App.css b/src/App.css
index 74b5e05..be998a7 100644
--- a/src/App.css
+++ b/src/App.css
@@ -36,3 +36,11 @@
transform: rotate(360deg);
}
}
+
+.likeButton {
+ background-color: rgb(231, 76, 60);
+ color: white;
+ padding: 0.8rem;
+ border-radius: 0.4rem;
+ cursor: pointer;
+}
diff --git a/src/App.tsx b/src/App.tsx
index a53698a..dc22bf6 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -1,24 +1,15 @@
import React from 'react';
import logo from './logo.svg';
import './App.css';
+import LikeButton from './LikeButton';
function App() {
return (
<div className="App">
<header className="App-header">
- <img src={logo} className="App-logo" alt="logo" />
- <p>
- Edit <code>src/App.tsx</code> and save to reload.
- </p>
- <a
- className="App-link"
- href="https://reactjs.org"
- target="_blank"
- rel="noopener noreferrer"
- >
- Learn React
- </a>
+ <LikeButton />
</header>
+
</div>
);
}
ランダム猫画像生成器
code:sh
cd ~/src
npx create-next-app random-cat --use-npm --example with-typescript
cd random-cat
npm run dev
3枚のネコ画像をランダムに表示
code:diff
diff --git a/pages/index.tsx b/pages/index.tsx
index 53decf0..5183ef4 100644
--- a/pages/index.tsx
+++ b/pages/index.tsx
@@ -1,8 +1,33 @@
import Link from 'next/link'
+import { useState } from 'react';
import Layout from '../components/Layout'
+const catImages = [
+ "https://cdn2.thecatapi.com/images/bpc.jpg",
+ "https://cdn2.thecatapi.com/images/eac.jpg",
+ "https://cdn2.thecatapi.com/images/6qi.jpg",
+];
+
+function randomCatImage() {
+ const index = Math.floor(Math.random() * catImages.length);
+ return catImagesindex;
+}
+
export default function IndexPage() {
+ const catImageUrl, setCatImageUrl = useState(
+ "https://cdn2.thecatapi.com/images/bpc.jpg"
+ );
+
+ function handleClick() {
+ setCatImageUrl(randomCatImage());
+ }
+
return (
- <h1>Hello Next.js 👋👋👋</h1>
+ <>
+ <button onClick={handleClick}>今日のねこ🐈</button>
+ <div>
+ <img src={catImageUrl} />
+ </div>
+ </>
);
}