重用函数类型的参数定义

Tre*_*Dev 1 typescript

在打字稿中有一种重用参数类型的方法,如下所示:

interface Box {
    create: (paramToReuse: (value: any) => void) => void
}
// is there a way to reference paramToResuse as a type? e.g.
let x: Box['create']['paramToReuse']
Run Code Online (Sandbox Code Playgroud)

这可以通过相反的方式完成:首先定义 paramToReuse,然后在 Box 的界面中引用它,但是可以按照我上面显示的方式完成吗?

Nic*_*wer 5

如果可以通过参数索引 ( 0) 而不是名称 ( ) 来引用它,则可以使用辅助类型Parameters"paramToUse"来完成,该类型接受一个函数并将其转换为参数的元组:

interface Box {
    create: (paramToReuse: (value: any) => void) => void
}

let x: Parameters<Box["create"]>[0] // x is of type (value: any) => void
Run Code Online (Sandbox Code Playgroud)

游乐场链接