最低限覚える必要のあるものだけ記載
function printName(obj: { firstName: string, lastName?: string }) {
return firstName + lastName;
}
printName({ firstName: "hoge", lastName: "taro" });
function printName(firstName: string, lastName: string = "hoge"): string {
return firstName + lastName;
}
printName("hoge", "taro");
function printName(
firstName: string,
formatter: (name: string) => string
): string {
return firstName + lastName;
}
function formatter(name: string): string {
return name + "san";
}
printName("hoge", formatter("taro"));
定義は (引数:型)=>返り値
明示的に型を記載しなくても勝手に推論してくれる機能を型推論と呼ぶ
const age = 10;
console.log(age.length); //エラーとなる。numberにはlengthが存在しない
開発者が型を知っている場合に明示的に型を指定することができる
const myCanvas = document.getElementById('main_canvas') as HTMLCanvasElement
as でやる。
別名でエイリアスを作る
type Point = {
x: number,
y: number
};
function printPoint(point: Point) {}
printPoint({ x: 100, y: 100 });
object キーと value でも型を指定することができる
type Label = {
[key: string]: string
};
const labels: Label = {
topTitle: "トップタイトル",
secondTitle: "セカンドタイトル"
};
class Queue<T> {
private array: T[] = []
push(item:T) {
this.array.push(item)
}
pop():T | undefined {
return this.array.shift()
}
}
const queue = new Queue<number>()
queue.push(111)
queue.push(112)
type Identity = {
id:number | string;
name:string
}
type Contact = {
email:string
phone:string
}
//union
type Employee = Identity & Contact
//intersection
type IdentityOrContact = Identity | Contact
interface User {
name:string;
social?:{
facebook:boolean
}
}
let uesr:User
user = {name:"aaa"}
//以下のsocialにオブジェクトがなかったとしてもエラーにならない。
console.log(user.social.facebook)
//同様のことは以下
function processUser(user?:User){
//userオブジェクトがなかったとしても以下エラーにならない
let name = user!.name
}
関数の引数で「number | string」があった時 if でどちらの型が来たかを確認すると、それ以降確認した型となる
function addOne(value: string | number) {
if (typeof value === "string") {
return Number(value) + 1;
}
return value + 1;
}
//propertyに指定する方法
type User = {
readonly name:string;
readonly gender:string;
}
type SubUser = {
name:string;
gender:string;
}
//Readonly<T>でT以下のプロパティは変更することができない
type ReadonlyUser = Readonly<SubUser>
any と同じような感じ。しかし、any とは違いプロパティを参照することができない。if 文で typeof 判定をした場合、プロパティを参照することができるようになる
const x:unkown = 123;
//エラー
console.log(x.toFixed(1))
if(typeof === 'number') {
//以下typeofを入れているのでエラーとならない
console.log(x.toFixed(1))
}
#以下コマンドにてファイルが作成
tsc --init
主要なもの
data = nullという感じで null を引数に入れることができなくなる。実施するにはlet date = Date | nullという感じで null を許容するような型設定をする必要がある。スペースのインデントであったりシングルクオートに揃えたりするもの。コードのフォーマットを自動でやる
npm install prettier --save-dev
.prettierrcというファイルを作成して利用する
コードのエラーの検知を行ってくれるもの
vite + react + tailwindcss の環境構築するための tips
npm create vite@latest #viteでcliを構築 色々聞かれこの時typescriptをreact-tsで選択可能
npm install -D eslint #eslintを入れる
npm init @eslint/config # eslintrcを作成するためのもの https://motamemo.com/programming/eslint-tips/eslint-init-config/
npm install -D prettier eslint-config-prettier #prettier
npm install -D tailwindcss postcss autoprefixer #tailwind
npx tailwindcss init -p
を実行し
# src/index.css
@tailwind base;
@tailwind components;
@tailwind utilities;
#eslintrc
...
extends: [
'plugin:react/recommended',
'plugin:@typescript-eslint/recommended',
'plugin:@typescript-eslint/recommended-requiring-type-checking',
'prettier',
],
上記を記載すればコードの解析やフォーマットの整形に必要なものは設定できている状態となる。ここでは eslint や prettier を詳細に書くことはないが、いづれ書きたいとは思う。。。