PHPで型クラスを書くとどうなるか考えてみた - Qiitaに続いてちゃんとジェネリクスとコンパイルがある言語のTypeScriptで型クラスを書いたらどうなるのか考えてみた。TypeScriptでは3つめのboolean
なのにstring
を渡している行がコンパイルエラーになった。
type Show<T> = (f: T) => string
const stringShow: Show<string> = (f: string) => f
const boolShow: Show<boolean> = (f: boolean) => f ? 'true' : 'false'
const quote = <T>(show: Show<T>) => (f: T) => '"' + show(f) + '"'
console.log(quote(stringShow)("hello")) //=> "hello"
console.log(quote(boolShow)(true)) //=> "true"
console.log(quote(boolShow)("hello")) //=> Argument of type '"hello"' is not assignable to parameter of type 'boolean'.