我想在另一个函数中引用一个函数的参数类型,但只使用它们的一个子集。
//params of bar should be same as foo, except p1 should be a different type
function foo(p1: string, p2: number, p3: boolean){
...
}
//i'd like to do something like this, though it's obviously not valid syntax
function bar(p1: string[], ...rest: Parameters<typeof foo>.slice(1)){
}
Run Code Online (Sandbox Code Playgroud)
有没有办法做到这一点?显然,仅使用 3 个参数手动完成并不难,但在我的实际代码中,我有更多参数,我不想重复它们。
type DropFirst<T extends unknown[]> = T extends [any, ...infer U] ? U : never
function bar(p1: string[], ...rest: DropFirst<Parameters<typeof foo>>) { }
// bar: (p1: string[], p2: number, p3: boolean) => void
Run Code Online (Sandbox Code Playgroud)
推断除第一个元组之外的所有元组元素的语法现在变得更简单。请参阅 Robby Cornelissen对 <4.0 版本的回答。
type CommonParams = [p2: number, p3: boolean];
function foo2(p1: string, ...rest: CommonParams){}
// foo2: (p1: string, p2: number, p3: boolean) => void
function bar2(p1: string[], ...rest: CommonParams) { }
// bar2: (p1: string[], p2: number, p3: boolean) => void
Run Code Online (Sandbox Code Playgroud)
命名元组可用于保留函数参数名称,因此没有有损转换。
| 归档时间: |
|
| 查看次数: |
700 次 |
| 最近记录: |