关于Function
和最佳实践
Function https://github.com/microsoft/TypeScript/blob/9ff24b6/lib/lib.es5.d.ts#L272-L304实际上,作为所有函数的超类型,类型安全性不足。你最好用一个替换它功能类型 https://www.typescriptlang.org/docs/handbook/functions.html#function-types- 请参阅下面的“解决方案”部分。
在上面的例子中,Function
不可分配给更狭窄的onClick
函数类型,这会导致手头的错误(游乐场示例 https://www.typescriptlang.org/play?#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgIilQ3wChSYBPMJOABRzAGc4BeOAb1LjggDsAwgBtgaANYAuOADEArnwzB+pAL4Bucmn5N4AZVkAjEMHjsAFB16CR4uCqkMIzAJRsAfNzhnPPADwHZGBh+OCoaVnwAoP58K2FRMVYOfnjxFTc4AHpMuAB3YAATWgByOQUYJT5i0OpaPgh4FCYmYABzPhQDIVpguDQbMTgACxQ+Au6oHx4+gbgQJCnfTKjgvg8eZ3JsuE6IADdaYBYmFHm4JCgcKB2WGCHaTAghIQh8vlaJUi0+HTnKVLEAAlRuMLlIyooQuYkHspMh0DAAHQAWQgsiYSAAogc+DBXKwMhxvkwnkhES9WmZ8P0EkgCgBCfDOFRfbRYPhSMxmGFIXFw4hI1HorE4mC+QEAFWRABkAEKBVaY7rzXEAGjgQox2N5MDc+IyewghXxfwBwLGEyyOQuVyAA).
此外提到的问题, https://github.com/Microsoft/TypeScript/issues/20007#issuecomment-405766256这是什么TypeScript 文档 https://www.typescriptlang.org/docs/handbook/2/functions.html#function说关于Function
:
这是一个无类型函数调用,通常最好避免,因为 any 返回类型不安全。如果需要接受任意函数但不打算调用它,则类型() => void
一般来说比较安全。
typescript-eslint https://github.com/typescript-eslint/typescript-eslint has 丢弃的 Function
与ban-types https://github.com/typescript-eslint/typescript-eslint/blob/v4.4.0/packages/eslint-plugin/docs/rules/ban-types.md rule, 发出以下消息 https://github.com/typescript-eslint/typescript-eslint/blob/1cb8ca4/packages/eslint-plugin/src/rules/ban-types.ts#L74-L81使用默认配置(另请参阅here https://github.com/typescript-eslint/typescript-eslint/blob/v4.4.0/packages/eslint-plugin/docs/rules/ban-types.md#default-options):
The Function
type 接受任何类似函数的值。它在调用函数时不提供类型安全,这可能是错误的常见来源。
如果您希望函数接受某些参数,则应该显式定义函数形状。
更好的解决方案
React 已经自带了内置事件处理程序类型 https://github.com/DefinitelyTyped/DefinitelyTyped/blob/927f70d/types/react/index.d.ts#L1303-L1316处理常见事件 https://reactjs.org/docs/events.html#supported-events.
For example
click
(
Playground https://www.typescriptlang.org/play?#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgIilQ3wChSYBPMJOABRzAGc4BeOAb1LjggDsAwgBtgaANYAuRMRgA6ALIQArkyQBRAG5I+MABIo+AEyFIoAHl0AVeQBkAQkpgx+akyG0wAfKQC+AbnI0fiZ4AGUlACMQYHh2AAoOXkERcTgfKQYIZgBKNm8eOO4eODMIx2c+OCoaVnwyp358JOFRMVYOfhbxH3zinjQUsTh3Ip4zAHp6it7soA):
type Props = {
onClick: React.MouseEventHandler<HTMLButtonElement>
};
const Submit = ({ onClick }: Props) => <button onClick={onClick}> click </button>
A more general alternative is to use
function types https://www.typescriptlang.org/docs/handbook/functions.html#function-types as follows:
type Props = {
onClick: (event: React.MouseEvent<HTMLElement>) => void
};
void
比any
。不可能意外地在回调中返回一个值,这可以通过any
.
总之,我们拥抱 TypeScript 的打字功能,而不是使用Function
or any
。
现在已知参数为MouseEvent
和返回类型void
,将其识别为回调。
Related
Typescript:如何定义方法参数中使用的函数回调的类型(作为任何函数类型,不是通用的) https://stackoverflow.com/questions/29689966/typescript-how-to-define-type-for-a-function-callback-as-any-function-type-no