我在下面的功能:
const fetchList = ({ current = 1, pageSize = 10 } = {}) => {/*...*/}
fetchList() // invoke
在打字稿中,我要输入文字,这是我这样做的唯一方法:
const fetchList=({current = 1, pageSize = 10}?: {current?: number; pageSize?: number} = {}) => {/*...*/}
fetchList() // invoke
但是我想像这样单独制作函数类型声明,以便可以重用,然后函数声明出错::
type FetchListType = ({ current, pageSize }?: { current?: number; pageSize?: number }) => void
const fetchList: FetchListType = ({ current = 1, pageSize = 10 } = {}) => {/*...*/}
如果解决此问题,则应像这样传递函数类型声明,使对象参数不可选
type FetchListType = ({ current, pageSize }: { current?: number; pageSize?: number }) => void
此结果我应该用空对象调用fetchList
:
fetchList({}) // should have a parameter
问题是:如何声明可以使我在不带参数的情况下调用函数的函数类型?
首先,原始实现未在TS 3.7.2中进行编译
const fetchList=({current = 1, pageSize = 10}?: {current?: number; pageSize?: number} = {}) => {/*...*/}
// Error - Parameter cannot have question mark and initializer
让我们专注于您要解决的问题。我试图在元级别上解决您的问题,但是到了我认为这是一个不同级别的问题。好像可以不带参数地调用函数一样,在此级别进行分解是错误的,这是典型的代码错误。我们不能破坏无法通过的东西。因此,TS在这里做得很好。
FetchListType
函数类型允许不带参数地调用函数,这也是您想要的。所以您的第一种类型是正确的:
type FetchListType = ({ current, pageSize }?: { current?: number; pageSize?: number }) => void
它定义了或者没有参数,或者将具有给定结构的参数。大!现在解决问题:
const fetchList: FetchListType = ({ current = 1, pageSize = 10 } = {}) => {/*...*/}
上面的函数对FetchListType
的实现有错误,该实现假定参数存在,但类型不能保证。类型是正确的,它满足具有带可选参数的函数的需要。现在我们只需要添加正确的实现,这样就可以处理参数的可选性质:
type FetchListType = ({ current, pageSize }?: { current?: number; pageSize?: number }) => void
const fetchList: FetchListType = (arg) => {
if (arg) {
arg // here arg is { current?: number; pageSize?: number }
} else {
// here arg is undefined
}
}
// also correct implementation which has default value of the argument:
const fetchList: FetchListType = (arg = { current: 1, pageSize: 10 }) => {
console.log(arg); // if arg will not be passed it will be { current: 1, pageSize: 10 }
}
总结。我们不能编写实现比类型强的假设的实现。类型不允许任何参数,实现需要处理。
我解决问题的方法是这样的:
type FetchListType = (search?: { current?: number; pageSize?: number }) => void
const fetchList: FetchListType = (search = {}) => {
const {current, pageSize} = {current: 1, pageSize: 10, ...search}
/*...*/
}
fetchList()