Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: useMemoizedFn return a plain function type #1470

Merged
merged 2 commits into from
Feb 25, 2022

Conversation

fanck0605
Copy link
Contributor

@fanck0605 fanck0605 commented Feb 23, 2022

[中文版模板 / Chinese template]

🤔 This is a ...

  • Bug fix

💡 Background and solution

我们考察如下代码

export default function App() {
  const fn = () => {
    console.log("hello");
  };

  fn.hello = "hello"; // fn: {():void,hello: string}

  const memoizedFn = useMemoizedFn(fn); 

  return (
    <div>
      <div>{`${fn.hello}` /* hello */}</div>
      <div>{`${memoizedFn.hello}` /* undefined */}</div>
    </div>
  );
}

TypeScript 推导出 memoizedFn.hello不可空string, 但实际访问则是 undefined
如果 memoizedFn.hello 还是个对象,继续使用 . 运算符,那么还会有更可怕的异常发生。

memoizedFn.current = function (this, ...args) {
return fnRef.current.apply(this, args);
} as T;

原来的代码,由于使用的类型强制转换,导致类型推导出现错误,我们这里的返回值类型,应该剔除 fn 对象中的所有属性,而只保留其函数的部分。

因此我们可以定义一个 ts type,它的泛型参数可以接受任意函数对象,然后转换成一个普通的函数

type PickFunction<T extends noop> = (
  this: ThisParameterType<T>,
  ...args: Parameters<T>
) => ReturnType<T>;

📝 Changelog

Language Changelog
🇺🇸 English
🇨🇳 Chinese

☑️ Self Check before Merge

⚠️ Please check all items below before review. ⚠️

  • Doc is updated/provided or not needed
  • Demo is updated/provided or not needed
  • TypeScript definition is updated/provided or not needed
  • Changelog is provided or not needed

@CLAassistant
Copy link

CLAassistant commented Feb 23, 2022

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you all sign our Contributor License Agreement before we can accept your contribution.
0 out of 2 committers have signed the CLA.

❌ fanck0605
❌ brickspert
You have signed the CLA already but the status is still pending? Let us recheck it.

Copy link
Collaborator

@awmleer awmleer left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@brickspert brickspert merged commit 3618ae6 into alibaba:master Feb 25, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants