简体   繁体   English

如何复制函数的参数和返回类型?

[英]How to copy parameters and return type of function?

I have function x and I have function y .我有函数x并且我有函数y How can I make function y have all the same parameter and return types as function x ?如何使函数y具有与函数x相同的参数和返回类型? Essentially I'd like to make them identical, except for their inner workings (everything in between { and } ).本质上,我想让它们相同,除了它们的内部工作原理( {}之间的所有内容)。

I know I can use Parameters<typeof x> and ReturnType<typeof x> but was wondering if there was a single utility that does everything in one hit.我知道我可以使用Parameters<typeof x>ReturnType<typeof x>但想知道是否有一个实用程序可以一键完成所有操作。

typeof x will give you the full type: typeof x会给你完整的类型:

const x = (a: string, b: number): boolean => { return true }

const y: typeof x = (a: string, b: number): boolean => { return false }

// leaving the individual types out, but they're still string, number, boolean
const implicitY: typeof x = (a, b) => { return false } 

// This misuse of `typeof x` shows typescript errors
const badY: typeof x = (a: number, b: string): boolean => { return 'hi' }

Playground link 游乐场链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何根据 Typescript 的输入参数定义一个 function 的返回类型? - How to define the return type of a function according to the input parameters with Typescript? 如何使用提供的参数推断 function 的返回类型? - How can infer return type of a function using the parameters supplied? TypeScript - 基于多个参数的函数返回类型 - TypeScript - Function return type based on multiple parameters 使用函数参数从返回类型中选择 - Pick from return type by using function parameters 根据可选参数推断返回类型 function - Infer the return type function based on optional parameters 基于参数推断function返回类型 - Inference of function return type based on parameters 如何键入需要返回对象副本同时更改其属性之一的类型的函数? - How to type a function that needs to return a copy of an object while also changing the type of one of its properties? 如何声明一个通用 function 返回一个 function (反应挂钩),其参数相同但返回类型与其参数不同 - How to declare a generic function that returns a function (react hook) with same parameters but different return type from its parameter 如何在typescript中输入一个function的参数? - How to type a function with parameters in typescript? 具有固定参数但推断返回类型的 TypeScript 函数类型 - TypeScript function type with fixed parameters but inferred return type
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM