How to binding a generic function in TypeScript

♀尐吖头ヾ 提交于 2019-12-11 04:09:52

问题


I'm trying to bind a generic function to a specific context and parameter, however I can't seem to be able to figure out the correct way to do it.

Here's my code:

interface A {}

interface Repository<T> {
  save(item: T): boolean;
} 

const updater = <T>(repo: Repository<T>, item: T) => {
  // do things and update
};

const items: A[] = [];
const repo: Repository<A> = {
  save(item: A) {
    /* do things */
    return true;
  }
}

items.forEach(updater<A>.bind(null, repo)); // Line with issue

The idea here would be to have a generic function which takes the repository as the first parameter and when bound would create a function suitable for use in forEach. However I get errors like ( expected and cannot find name 'bind'

I'm not entirely sure if there's something wrong with my syntax there or I'm missing anything.

I've also tried:

updater.bind(null, repo)

However this does not work with 3.2 option strictBindCallApply because it assumes type parameter T={}

Does anyone know the correct way to do this?

Playground link

来源:https://stackoverflow.com/questions/55950126/how-to-binding-a-generic-function-in-typescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!