【发布时间】:2021-10-01 22:39:40
【问题描述】:
我设置了一个名为useField.ts 的相当简单的钩子,它的定义方式如下:
type CheckFunction = <T>(input: T, ...args: unknown[]) => unknown
export const useField = <T>(
input: T,
...checkFunctions: CheckFunction[]
) => {
// .... and the code goes here, but irrelevant for the question
}
之后我开始在useField.test.tsx 中通过以下方式编写测试:
import { renderHook } from '@testing-library/react-hooks'
import { useField } from '../useField'
describe('useField error functions', () => {
const emailRegex = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/gi
const isValidEmail = (input: string): boolean => !!input.match(emailRegex)
test('Basic checkFunction', () => {
const { result } = renderHook(() => useField('valid@email.com', isValidEmail)
// ^ I get a type-error here
})
})
我尝试通过isValidEmail 函数的行有以下typescript 错误:
Argument of type '(input: string) => boolean' is not assignable to parameter of type 'CheckFunction'.
Types of parameters 'input' and 'value' are incompatible.
Type 'T' is not assignable to type 'string'.
现在可以通过将checkFunctions 的定义分配给any 从技术上解决这个问题,但我要提防这件事,因为它有点违背了类型检查的目的。
我也考虑过使用泛型,但问题是,参数可以是各种类型,并且不能用单个泛型的数组来表达
知道我在这里做错了什么吗?因为从逻辑的角度来看,unknown 的用法在这里似乎是正确的。
【问题讨论】:
标签: typescript reactjs typescript react-hooks typescript-typings react-testing-library