LoginSignup
4
2

More than 3 years have passed since last update.

typescriptで高階関数を使いたくなった時に思い出すための覚書

Last updated at Posted at 2020-01-07

注意

筆者は高階関数に詳しいわけではないので認識が間違っている場合があります。

高階関数とは

Wiki

第一級関数をサポートしているプログラミング言語において、関数(手続き)を引数に取る関数のことである。

と書かれている。また、別の記事によると、戻り値によって関数(手続き)を返却する関数も
該当するらしい。

つまりは、よくみる所の。

  • 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 & プログラミングの世界は奥が深い

4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2