関数の型
// TypeScript
const test:(a:number, b: number) => number = (a, b) => a + b
// Scala
val test: (Int, Int) => Int = (a, b) => a + b
// Java
BiFunction<Integer, Integer, Integer> test = (a, b) -> a + b;
Java の関数は第一級オブジェクトではないが、関数型インターフェースというものを利
用して第一級オブジェクトっぽく見せている。
const a: any= 666 // any
const b: any = 'danger' // any
const c = a + b // any
any 型
プログラマの敗北
any を使うと TypeScript が持つ型の優位性が無くなり、ただの JavaScript と同じ振る
舞いになってしまう。そのため、やむをえない場合以外使うべきではない
型を無視するためのものなので、Java、Scalaにはない
型エイリアス
ある型を指し示す別名を宣言することができる
type User ={
name: string
}
class User2 {
constructor(public readonly name: string) {}
}
const a: User = new User2('bob') // 構造的型付けなので代入可能
12.
型エイリアス
一応 Scala でも可能
typeUser = { def name: String }
case class User2(name: String) {}
val user: User = User2("bob")
Java には存在しない
ジェネリック型パラメータに制限を加えられる
型境界
class A {private type = 'A' }
class B {}
class C extends A {}
class Some<T extends A> {
constructor(public readonly value: T) {}
}
const someB = new Some(new B())
// 型 'B' の引数を型 'A' のパラメーターに割り当てることはできません。
// プロパティ 'type' は型 'B' にありませんが、型 'A' では必須です。
const someC = new Some(new C())
function test(a: number| string | boolean | null): void {
if (a == null) return console.log('null')
const b = a // const b: string | number | boolean
if (typeof a === 'number') return console.log('number')
const c = a // const c: string | boolean
if (typeof a === 'string') return console.log('string')
const d = a // const d: boolean
}
型の絞り込み
TypeScript はフローベースの型推論を行う。これにより、型の絞り込みを提供する。
23.
trait 積木
case object三角の積み木 extends 積木
case object 四角の積み木 extends 積木
case object 丸の積み木 extends 積木
trait Tree[T]
case class Leaf[T](value: T) extends Tree[T]
case class Branch[T](value: Seq[Tree[T]]) extends Tree[T]
タグ付き合併型
TypeScript で代数的データ型を表現する方法
代数的データ型とは、総体と、それを構成する構成子からなるデータ構造である
オプション (?) 修飾子
TypeScriptに、あるものが省略可能であることを伝える修飾子
function test(a?: number): number {
return a
}
// Type 'number | undefined' is not assignable to type 'number'.
// Type 'undefined' is not assignable to type 'number'
function test2(a?: number): number {
if (a === undefined) {
return 0
} else {
return a
}
}