関数の型// TypeScriptconst test:(a:number, b: number) => number = (a, b) => a + b// Scalaval test: (Int, Int) => Int = (a, b) => a + b// JavaBiFunction<Integer, Integer, Integer> test = (a, b) -> a + b;Java の関数は第一級オブジェクトではないが、関数型インターフェースというものを利用して第一級オブジェクトっぽく見せている。
function test(a: number| string | boolean | null): void {if (a == null) return console.log('null')const b = a // const b: string | number | booleanif (typeof a === 'number') return console.log('number')const c = a // const c: string | booleanif (typeof a === 'string') return console.log('string')const d = a // const d: boolean}型の絞り込み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}}