[TypeScript] express

$ sudo npm install -g express-generator
$ npx express -e express_app
$ cd express_app
$ npm install
$ npm run start
http://192.168.34.10:3000/

$ sudo npm install -g express-generator-typescript
$ npx express-generator-typescript express_type_app
$ cd express_type_app
$ npm run start:dev

$ npm install ejs
src/routes/hello.ts

import { Request, Response, Router } from 'express'

const router:Router = Router()

router.get('/', function(req:Request,
		res:Response):void{
	res.render('hello', {
		header:'Hello page',
		title: 'Hello!!',
		msg: 'This is HEllo page!'
	})
})
export default router

src/Server.ts

import helloRouter from './routes/hello'

app.set('view engine', 'ejs')
app.use('/hello', helloRouter)

src/views/hello.ejs

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title><%= title %></title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
</head>
<body>
  <h1 class="bg-primary text-white p-2"><%= header %></h1>
  <div class="container py-2">
  	<h2 class="mb-3"><%= title %></h2>
  	<div class="alert alert-primary">
  		<%= msg %>
  	</div>
  </div>
</body>
</html>

http://192.168.34.10:3000/hello

なかなか凄いわ

[TypeScript] Vue.js

$ sudo npm install -g @vue/cli
$ npm install –save vue-class-component
$ npx vue create vue3_type_app
Manually select features
◯ TypeScript (スペースキーでセットする)
❯ 3.x
❯ ESLint with error prevention only
❯◉ Lint on save
❯ In dedicated config files

App.vue

<template>
  <HelloWorld />
</template>

HelloWorld.vue

<script lang="tsx">
import { VNode } from 'vue'
import { Vue } from 'vue-class-component'

export default class HelloWorld extends Vue {
  msg = "Vue sample."
  val = 1

  doAction():void {
    this.val += 1
  }

  render():VNode {
    return(<div>
      <h1 class="bg-info text-white p-2">{this.msg}</h1>
      <div class="container">
        <h2 class="my-3">number counter.</h2>
        <div class="alert alert-info">
          <h3 onClick={this.doAction}>{this.val} count.</h3>
        </div>
      </div>
    </div>)
  }

}
</script>

node_modules/vue-class-component/lib”‘ has no exported member ‘Vue’.

うーん、上手くいかんな…

[TypeScript] Reactを使う

$ npx create-react-app react_typescript_app –template typescript
$ cd react_typescript_app
$ npm start

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="manifest" href="%OUBLIC_URL%/manifest.json"/>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
</head>
<body>
  <noscript>You need to enable JavaScript to run this app.</noscript>
  <div id="root"></div>
</body>
</html>

App.tsx

import {useState, ReactElement} from 'react';
import './App.css';

function App():ReactElement {
  const [msg, setMsg] = useState("this is sample message.")
  return (
      <div>
        <h1 className="bg-primary text-white p-2">React sample</h1>
        <div className="container">
        <h2 className="my-3">click button!</h2>
        <div className="alert alert-primary">
            <div className="row px-2">
              <h3 id="msg">{msg}</h3>
            </div>
        </div>
        </div>
      </div>
  );
} 


export default App;

### 電卓

import {ChangeEvent, KeyboardEvent, useState, ReactElement} from 'react';
import './App.css';

function App():ReactElement {
  const [val, setVal] = useState(0)
  const [data, setData] = useState<number[]>([])

  const doChange = (event:ChangeEvent):void => {
    const ob = event.target as HTMLInputElement
    const re = Number(ob.value)
    setVal(re)
  }
  const doAction = ():void => {
    const arr:number[] = []
    for(let item of data)
      arr.push(item)
    arr.push(val)
    setData(arr)
    setVal(0)
  }
  const doType = (event:KeyboardEvent):void => {
    if(event.code == 'Enter'){
      doAction()
    }
  }

  let total = 0

  return (
      <div>
        <h1 className="bg-primary text-white p-2">React sample</h1>
        <div className="container">
        <h2 className="my-3">click button!</h2>
        <div className="alert alert-primary">
            <div className="row px-2">
              <input type="number" className="col"
                onChange={doChange} onKeyPress={doType} value={val} />
              <button onClick = {doAction}
                className="btn btn-primary col-2">
                  Click!
              </button>
            </div>
        </div>
        <table className="table">
          <thead><tr><th>value</th><th>total</th></tr></thead>
          <tbody>
          {data.map((v,k)=>{
            total += v
            return <tr key={k}><td>{v}</td><td>{total}</td></tr>
          })}
          </tbody>
        </table>
        </div>
      </div>
  );
} 


export default App;

Reactは比較的わかりやすいか。

[TypeScript] クライアントサイド

html

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Document</title>
	<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
	<script src="main.js"></script>
</head>
<body>
	<h1 class="bg-primary text-white p-2">web sample</h1>
	<div class="container">
		<h2 class="my-3">web sample</h2>
		<div class="alert alert-primary">
			<p id="msg">wait...</p>
		</div>
	</div>
</body>
</html>

index.ts

let msg:HTMLParagraphElement

const html = `<h2>This is message</h2>
	<p>これはTypeScriptで表示したコンテンツです。</p>`

window.addEventListener('load', ()=> {
	msg = document.querySelector('#msg')
	msg.innerHTML = html
})
let msg:HTMLParagraphElement

const html = `<h2><a id="title">This is message</a></h2>
	<p>これはTypeScriptで表示したコンテンツです。</p>`

window.addEventListener('load', ()=> {
	msg = document.querySelector('#msg')
	msg.innerHTML = html
	const title:HTMLAnchorElement = document.querySelector('#title')
	title.href = 'http://google.com'
})

Firebaseで開発する

1. Firebaseでプロジェクトを作成
プロジェクト名: typescript-hpscript
google analytics: off

2.Realtime database
create database
location: United States(us-central)
start in test mode

edit rule

{
  "rules": {
    ".read": true,
    ".write": true,
    "boards": {
      ".indexOn":["posted"]
    }
  }
}

index.html

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Document</title>
	<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
	<script src="main.js"></script>
</head>
<body>
	<h1 class="bg-primary text-white p-2">Board</h1>
	<div class="container">
		<h2>send message:</h2>
		<div class="alert alert-primary">
			<div>
				<label>your nickname:</label>
				<input type="text" id="nickname" class="form-control form-control-sm"/>
			</div>
			<div>
				<label>message:</label>
				<input type="text" class="form-control" id="message"/>
			</div>
			<button class="btn btn-primary mt-2" id="btn">
			fetch</button>
			</div>
			<table class="table mb-4" id="table"></table>
			<div class="text-center">
				<button class="btn btn-danger mb-4" id="delete">delete all</button></div>
	</div>
</body>
</html>

index.ts

let nickname: HTMLInputElement
let message:HTMLInputElement
let table:HTMLTableElement
const url = ‘https://typescript-hpscript.firbaseio.com/boards.json’

function doAction(){
const data = {
nickname: nickname.value,
message: message.value,
posted: new Date().getTime()
}
sendData(url, data)
}

function doDelete():void {
fetch(url, {
method: ‘DELETE’
}).then(res=> {
console.log(res.statusText)
getData(url)
})
}

function sendData(url:string, data:object){
fetch(url, {
method: ‘POST’,
mode: ‘cors’,
headers: {
‘Content-Type’:’application/json’
},
body: JSON.stringify(data)
}).then(res=>{
console.log(res.statusText)
getData(url)
})
}

function getData(url:string){
fetch(url).then(res=>res.json()).then(re=> {
let result = `

Message Nickname posted `
let tb = ”
for(let ky in re){
let item = re[ky]
tb = ‘

‘ + item[‘message’] + ‘ ‘
+ item[‘nickname’] + ‘ ‘
+ new Date(item[‘posted’]).toLocaleString()
+ ‘

‘ + tb
}
result += tb + ‘


table.innerHTML = result
})
}

window.addEventListener(‘load’, ()=> {
message = document.querySelector(‘#message’)
nickname = document.querySelector(‘#nickname’)
table = document.querySelector(‘#table’)

const btn : HTMLButtonElement = document.querySelector(‘#btn’)
btn.onclick = doAction
const del :HTMLButtonElement =
document.querySelector(‘#delete’)
del.onclick = doDelete
getData(url)
})
[/code]

ちょっと上手くいかんな

[TypeScript] 重要機能

### 名前空間
– exportで外部から使えるようにする

namespace myapp {
    namespace foundation {
        export interface printable {
            print():void
        }

        export interface stringable {
            getString():string
        }
    }

    export type Person = {
        name:string
        age:number
    }

    export class MyData implements
        foundation.printable,
        foundation.stringable {
            people:Person[] = []

            constructor(){}

            add(nm:string, ag:number){
                this.people.push({name:nm, age:ag})
            }

            print():void {
                console.log('*** mydata ***\n' + this.getString())
            }
            getString():string {
                let res = '[\n'
                for (let item of this.people){
                    res += ' "' +item.name+ ' (' + item.age + ')",\n'
                }
                return res + ']'
            }
        }
}

const mydata = new myapp.MyData()
mydata.add('taro', 39)
mydata.add('hanako', 28)
mydata.add('sachiko', 17)
mydata.add('jiro', 6)
mydata.print()

### モジュールとプログラムの分割
外部公開: export element
読み込み: import (element) from resources

src/lib.ts

export interface printable {
    print():void
}

export interface stringable {
    getString():string
}

export type Person = {
    name:string
    age:number
}

export class MyData implements printable, stringable {
        people:Person[] = []

        constructor(){}

        add(nm:string, ag:number){
            this.people.push({name:nm, age:ag})
        }

        print():void {
            console.log('*** mydata ***\n' + this.getString())
        }
        getString():string {
            let res = '[\n'
            for (let item of this.people){
                res += ' "' +item.name+ ' (' + item.age + ')",\n'
            }
            return res + ']'
        }
    }

index.ts

import { MyData } from './lib'

const mydata = new MyData()
mydata.add('taro', 39)
mydata.add('hanako', 28)
mydata.add('sachiko', 17)
mydata.add('jiro', 6)
mydata.print()

$ npm run build
$ node dist/main.js
*** mydata ***
[
“taro (39)”,
“hanako (28)”,
“sachiko (17)”,
“jiro (6)”,
]

### ミックスイン
複数のクラスを継承して機能を引き継ぐ

function applyMixins(derivedCtor: any, constructors: any[]){
    constructors.forEach((baseCtor) => {
        Object.getOwnPropertyNames(baseCtor.prototype).forEach((name) => {
            Object.defineProperty(
                derivedCtor.prototype,
                name,
                Object.getOwnPropertyDescriptor(baseCtor.prototype, name) || Object.create(null)
            );
        });
    });
}

class Person {
    name:string = ''
    title:string = ''

    setPerson(nm:string, tt:string):void {
        this.name = nm
        this.title = tt
    }
}

class Pet {
    kind:string = ''
    age:number = 0

    setPet(k:string, ag:number):void {
        this.kind = k
        this.age = ag
    }
}

class Me {
    print():void {
        console.log(this.name + ' (' + this.age + ')\n'
            + '"' + this.title + '". pet is ' + this.kind + '!')
    }
}

interface Me extends Person, Pet {}
applyMixins(Me, [Person,Pet])

const me = new Me()
me.setPerson('taro', 'designer')
me.setPet('cat', 2)
me.print()

### 非同期処理とasync/await
実行したら後はどれがいつ終わるかわからない

function action(dt:number){
    return new Promise(resolve=>{
        setTimeout(()=> {
            console.log('fished promise!')
            resolve("delay:" + dt)
        }, dt)
    })
}

action(2000).then(res=>console.log(res))
action(1000).then(res=>console.log(res))
action(500).then(res=>console.log(res))

awaitは非同期でも処理が完了するまで待つ

async function doit(){
    let re1 = await action(2000)
    console.log(re1)
    let re2 = await action(1000)
    console.log(re2)
    let re3 = await action(500)
    console.log(re3)
}
doit()

### ネットワークアクセス
fetch().then(response=> hoge) と書く

function getData(url:string){
    fetch(url).then(res=>res.text()).then(re=>{
        console.log(re)
    })
}

const url = 'https://tuyano-dummy-data.firebaseio.com/message.json'
getData(url)

firebaseはCORSを解放しているが、解放していないサイトも多い

function getData(url:string){
    fetch(url).then(res=>res.json()).then(re=>{
        for (let item of re){
            console.log(item)
        }
    })
}

const url = 'https://tuyano-dummy-data.firebaseio.com/sample_data.json'
getData(url)

### ネットワークに同期アクセス
アクセスを非同期化する

async function getData(url:string){
    const response = await fetch(url)
    const result = await response.json()
    for(let item of result){
        console.log(JSON.stringify(item))
    }
}

const url = 'https://tuyano-dummy-data.firebaseio.com/sample_data.json'
getData(url)

### POST送信

async function getData(url:string, obj:object){
    await fetch(url, {
        method: 'POST',
        mode: 'cors',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(obj)
    })
    const response = await fetch(url)
    const result = await response.json()
    console.log(result)
}

const url = "https://tuyano-dummy-data.firebaseio.com/sample_data.json"

const obj = {
    title: 'hello!',
    message: 'This is sample message!'
}

getData(url, obj)

なるほど、TypescriptというよりJavaScriptでも重要なことやな

[TypeScript] 型

### マップ型
stringのキーのマップ型

type stringArray = {
    [key in string]: string
}

const data1:stringArray = {
    'start': 'start',
    'middle': 'middle',
    'end': 'end'
}

data1['finish'] = '**end**'
data1[100] = 'ok'
console.log(data1)

enum

enum human {name='name', mail='mail'}

type HumanMap = {
    [key in human]: string
}

const taro:HumanMap = {
    name: 'taro',
    mail: 'taro@yamada'
}
console.log(taro)
const hana:HumanMap = {
    name: 'hanako',
    mail: 'hanak@gmail.com'
}
console.log(hana)

ユニオン型

class Student {
    name:string
    school:string
    grade:number

    constructor(nm:string, sc:string, gr:number){
        this.name = nm
        this.school = sc
        this.grade = gr
    }

    print():void{
        console.log('<< ' + this.name + ',' +
            this.school + ':' + this.grade + ' >>')
    }
}
class Employee {
    name: string
    title: string
    department:string

    constructor(nm:string, tt:string, dp:string){
        this.name = nm
        this.title = tt
        this.department =dp
    }

    print():void {
        console.log(this.name + '[' + this.title + 
            ',' + this.department + ']')
    }
}

type People = Student | Employee

const taro:People = new Student('taro', 'high school', 3)
const hana:People = new Employee('hanako', 'president', 'sales')
const sachi:People = new Student('schiko', 'jinir-high school', 1)
const jiro:People = new Employee('jiro', 'director', 'labo')

const data:People[] = [taro, hana, sachi, jiro]
for(let item of data){
    item.print()
}

ユニオン型を個別に処理

class Human {
    data: People[] = []

    add(item:People):void {
        this.data.push(item)
    }
    print():void {
        for(let item of this.data){
            let ob
            switch(item.constructor.name){
                case 'Student':
                ob = item as Student
                console.log(ob.name + ', ' + ob.school
                    + '(' + ob.grade + ')')
                break
                case 'Employee':
                ob = item as Employee
                console.log(ob.name + ':' + ob.title
                    + ':' + ob.department)
                break
                default:
                console.log('cannot print.')
            }
        }
    }
}

### テンプレートリテラル
${}で埋め込む

const data = [10, 20, 30]
const msg = `data is [${data}]`
console.log(msg)
const result = `total is ${data[0]+data[1]+data[2]} !`
console.log(result)

### テンプレートリテラル型

type val_name = "sample"|"private"|"public"
type data_type = `${val_name}_data`
type prop_type = `${val_name}_property`
type method_type = `${val_name}_method`

const s:data_type = "sample_data"
const t:prop_type = "public_property"
const u:method_type = "private_method"
const v:data_type = "personal_data"

### レコード型

type prop_name = 'name' | 'mail' | 'age'
type Person = Record<prop_name, string|number>

const taro:Person = {
    name: 'taro',
    mail:'taro@gmail.com',
    age: 39
}

console.log(taro)

### Pick型

type person_data = {
    name:string,
    mail:string,
    address:string,
    age:number
}

type person_keys = 'name' | 'age'
type human_keys = 'name' | 'mail' | 'address'

type person = Pick<person_data, person_keys>
type human = Pick<person_data, human_keys>

const taro:person = {
    name: 'taro',
    age: 39
}
const hana:human = {
    name: 'hanako',
    mail: 'hanako@gmail.com',
    address: 'chiba'
}
console.log(taro)
console.log(hana)

### イテレータ

class MyData<T> {
    data:T[ ] = []

    constructor(...data: T[]){
        this.data = data
    }

    add(val:T) {
        this.data.push(val)
    }

    [Symbol.iterator](){
        let pos = 0;
        let items = this.data;

        return {
            next(): IteratorResult<T>{
                if(pos < items.length) {
                    return {
                        done: false,
                        value: items[pos++]
                    }
                } else {
                    return {
                        done: true,
                        value: null
                    }
                }
            }
        }
    }
}
const data = new MyData<string>('one','two','three')

for(let item of data){
    console.log(item)
}

OKなのかNGなのかすらわからん

[TypeScript] メモアプリ

index.html

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Document</title>
	<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
	<script src="main.js"></script>
</head>
<body>
	<h1 class="bg-primary text-white p-2">Memo page</h1>
	<div class="container">
		<p class="h5">type message:</p>
		<div class="alert alert-primary">
			<input type="text" class="form-control" id="message">
			<button class="btn btn-primary mt-2" id="btn">
			Save</button>
		</div>
		<table class="table" id="table"></table>
		<div class="text-center">
			<button class="btn btn-danger mt-4" id="initial">
				Initialize
			</button>
		</div>
	</div>
</body>
</html>

index.ts

let table:HTMLTableElement
let message:HTMLInputElement

function showTable(html:string){
	table.innerHTML = html
}

function doAction(){
	const msg = message.value
	memo.add({message:msg, date:new Date()})
	memo.save()
	memo.load()
	showTable(memo.getHtml())
}

function doInitial(){
	memo.data = []
	memo.save()
	memo.load()
	message.value = ''
	showTable(memo.getHtml())
}

type Memo = {
	message:string,
	date:Date
}

class MemoData {
	data:Memo[] = []

	add(mm:Memo):void {
		this.data.unshift(mm)
	}

	save():void {
		localStorage.setItem('memo_data', JSON.stringify(this.data))
	}
	load():void{
		const readed = JSON.parse(localStorage.getItem('memo_data'))
		this.data = readed ? readed : []
	}

	getHtml():string {
		let html = '<thead><th>memo</th><th>data</th></thead><tbody>'
		for(let item of this.data){
			html += '<tr><td>' + item.message + '</td><td>'
				+ item.date.toLocaleString() + '</td></tr>'
		}
		return html + '</tbody>'
	}
}

const memo = new MemoData()

window.addEventListener('load', ()=> {
	table = document.querySelector('#table')
	message = document.querySelector('#message')
	document.querySelector('#btn').addEventListener('click', doAction)
	document.querySelector('#inital').addEventListener('click', doInitial)
	memo.load()
	showTable(memo.getHtml())
})

これなんだよな やりたいこと

[TypeScript] クラス2

### インターフェイス

interface Human {
    name:string
    print():void
}

class Person implements Human {
    name:string = 'no-name'
    mail:string
    age:number

    constructor(name:string, mail:string = 'no-mail', age:number = -1){
        this.name = name
        this.mail = mail
        this.age = age
    }

    print():void {
        console.log(this.name + '(' + this.mail + ',' + this.age + ')')
    }
}

class Student implements Human {
    name:string = 'no-name'
    school?:School
    grade?:number

    constructor(name:string,school?:School, grade?:number){
        this.name = name
        this.school = school
        this.grade = grade
    }

    print():void {
        let gd:string = this.grade ? String(this.grade) : '-'
        console.log(this.name + '(' + this.school + ' school: ' + gd + ' grade)') 
    }
}

const taro:Person = new Person('taro', 'taro@yamada', 39)
const hanako:Student = new Student('hanako', School.high, 39)
const sachiko:Person = new Person('sachiko')
const jiro:Student = new Student('jiro')

const data:Human[] = [taro, hanako, sachiko, jiro]

for(let item of data){
    item.print()
}

### インターフェイスの継承

interface People extends Human {
    birth:Date
}

class Employee implements People {
    name:string = 'no-name'
    company:string = ''
    birth:Date = new Date()

    constructor(nm:string, cm:string, bth:Date){
        this.name = nm
        this.company = cm
        this.birth = bth
    }

    print():void {
        console.log(this.name + ' [' + this.company + ']')
    }
}

const ichiro = new Employee('ichiro',
    'Baseball Inc.', new Date('1982/10/10'))
ichiro.print()

### 静的メンバー

class StaticHuman {
    static fullname:string
    static age:number
    
    static set(nm:string, ag:number):void {
        this.fullname = nm
        this.age = ag
    }

    static print():void {
        console.log(this.fullname + '(' + this.age + ')')
    }
}

StaticHuman.set('taro',39)
StaticHuman.print()
StaticHuman.set('hanako',29)
StaticHuman.print()

### パラメータープロパティ

class Human {
    constructor(readonly name:string, readonly age:number){

    }

    print():void {
        console.log(this.name + '(' + this.age + ')')
    }
}

const taro = new Human('taro', 39)
taro.print()
const hana = new Human('hanako', 28)
hana.print()

### 総称型

class Data<T> {
    data?:T[]

    constructor(...item:T[]){
        this.data = item
    }

    print():void {
        if(this.data) {
            for(let item of this.data){
                console.log(item)
            }
        } else {
            console.log('no data...')
        }
    }
}

const data1 = new Data<string>('one','two','three')
const data2 = new Data<number>(123,456,78,90)
data1.print()
data2.print()

### ユーティリティ型
Readonly, Required, Partial

type Human = {
    name:string
    mail?:string
    age?:number
}

class Person {
    human:Required<Human>

    constructor(nm:string, ml:string, ag:number){
        this.human = {name:nm, mail:ml, age:ag}
    }

    print():void {
        console.log(this.human.name
            + ' (' + this.human.age + '::'
            + this.human.mail + ')')
    }
}
const taro = new Person('taro', 'taro@yamada', 39)
taro.print()

OK

[TypeScript] クラス1

### クラス

class Person {
    name:string = 'no-name'
    mail?:string
    age?:number
    print():void {
        const ml:string = this.mail ? this.mail : 'no-mail'
        const ag:number = this.age ? this.age : -1
        console.log(this.name + '(' + ml + ',' + ag + ')')
    }
}

const taro = new Person()
taro.name = 'taro'
taro.mail = 'taro@gmail.com'
taro.age = 39
taro.print()

### コンストラクタ

class Person {
    name:string = 'no-name'
    mail?:string
    age?:number

    constructor(name:string, mail:string = 'no-mail', age:number = -1){
        this.name = name
        this.mail = mail
        this.age = age
    }

    print():void {
        console.log(this.name + '(' + this.mail + ',' + this.age + ')')
    }
}

const taro = new Person('taro', 'taro@gmail.com', 39)
const hanako = new Person('hanako', 'hanako@gmail.com')
const sachiko = new Person('sachiko')

taro.print()
hanako.print()
sachiko.print()

### インスタンスのクラスを調べる

console.log(taro instanceof Person === hanako instanceof Person === true)

console.log(taro.constructor.name)
console.log(hanako.constructor.name)
console.log(Person.name)

### クラスの継承
extendsで継承する

enum School {
    junior='junior',
    juniorHigh = 'juniorHigh',
    high = 'high',
    other = 'other'
}

class Student extends Person {
    school?:School
    grade?:number

    constructor(name:string, school:School, grade:number){
        super(name)
        this.school = school
        this.grade = grade
        switch(school){
            case School.junior:
            this.age = 6 + this.grade; break
            case School.juniorHigh:
            this.age = 12 + this.grade; break
            case School.high:
            this.age = 15 + this.grade; break
            default:
            this.age = -1
        }
    }
}

const taro = new Person('taro', 'taro@gmail.com', 39)
const hanako = new Student('hanako', School.high, 2)

taro.print()
hanako.print()

### メソッドのオーバーライド
– 継承しているクラスの中にメソッドを追加する

    print():void {
        let gd:string = this.grade ? String(this.grade) : '-'
        switch(this.grade){
            case 1:gd += 'st'; break
            case 2:gd += 'nd'; break
            case 3:gd += 'rd'; break
            default: gd += 'th'
        }
        console.log(this.name + '(' + this.school + ' school: ' + gd + ' grade)')
    }

### アクセス修飾子
public: 外部から自由にアクセス
protected: クラスおよびクラスを継承したサブクラス
private: クラス内のみ

    protected name:string = 'no-name'
    private mail:string
    public age:number

### setterとgetter

class Student extends Person {
    school?:School
    private grade_num:number = -1
    get gradeN():number {
        return this.grade_num
    }
    set gradeN(n:number){
        this.grade_num = n
        this.grade = String(n)
    }
    private gr_str:string = ''
    get grade(): string {
        return this.gr_str
    }
    private set grade(pr:string){
        let gd = pr
        switch(this.gradeN){
            case 1: gd += 'st'; break
            case 2: gd += 'nd'; break
            case 3: gd += 'rd'; break
            default: gd += 'th'
        }
        this.gr_str = gd
    }

    constructor(name:string, school:School, grade:number){
        super(name)
        this.school = school
        this.gradeN = grade
    }

    print():void {
        let gd:string = this.grade ? String(this.grade) : '-'
        console.log(this.name + '(' + this.school + ' school: ' + gd + ' grade)')
    }
}

ふむ