注意
筆者は高階関数に詳しいわけではないので認識が間違っている場合があります。
高階関数とは
第一級関数をサポートしているプログラミング言語において、関数(手続き)を引数に取る関数のことである。
と書かれている。また、別の記事によると、戻り値によって関数(手続き)を返却する関数も
該当するらしい。
つまりは、よくみる所の。
- callback
- カリー化
みたいなものだろうか。。。
callbackの定義方法について
callbackをtypescriptで引数として定義する場合、
どんなふうに書いておいたらカッコいいのかな。と思い、Array Interfaceのts.d
を覗いてみた。
Array Interface(抜粋)
interface Array<T> {
forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void;
/**
* Calls a defined callback function on each element of an array, and returns an array that contains the results.
* @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
map<U>(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[];
/**
* Returns the elements of an array that meet the condition specified in a callback function.
* @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
filter<S extends T>(callbackfn: (value: T, index: number, array: T[]) => value is S, thisArg?: any): S[];
}
よく使う、map, filter, forEachあたり
というわけで
callback
const callback = (fn: (arg1: string) => void) => {
fn("Hello, World")
}
const str = (fn: (arg1: number) => string | unknown) => {
const s = fn(100)
if (typeof s == "string") {
console.log(s.toLocaleLowerCase())
}
}
悪い例として、const f = (fn: Function) => {}
のように書くこともできるが、
この場合だと戻り値の型がanyとなってしまう。
特定の型を返す関数以外受け付けないようにするため、上記のような書き方にする。
カリー化
イマイチカリー化は使いどころがわかっていないので、雑なサンプル。
(今までは、必要があったら後から実行する関数を返すようにしたりしていた)
const curry = (num: number) => {
return (str: string) => {
return num + Number(str)
}
}
脱線
コールバックのところで、戻り値の型をstring | unknown
にしていたかと思うが、
unknownってなんだろうと思って調べたところ非常にわかりやすい記事があった。
TypeScript 3.0のunknown型 - タイプセーフなany
簡単に理解するならば、anyの場合は実行時エラーとなっていたものを、unknownとできるならば
実行時エラーではなく、コンパイルエラーとして処理することができるということかな。。。
typescript & プログラミングの世界は奥が深い