打字稿如何键入提示功能
我想在打字稿中键入我的函数,如下所示:
// would like to remove this type
type FN<TArgs, TReturn> = (args: TArgs) => TReturn;
interface Args {
itemWeight: number;
quantity: number;
}
const calcTotalWeight: FN<Args, number> = ({ itemWeight, quantity }) => itemWeight * quantity;
是否有内置的通用通用力可以提供该实用程序?目前,我已经像上面一样创建了一个,但是我觉得这可能是一个非常普遍的用例。例如,React具有fc
。
我确实注意到,这种类型需要您的功能是一致的,但这是这里的重点。具有单一函数是通常的,而单个参数是对象,以便我们可以具有“命名”参数。
有人知道这是否存在,还是对这是个好主意的想法?
扩展:
有人知道如何提出通用可选的第二个论点,以便在不提供的情况下推断出来吗?例如:
const calcTotalWeight: FN<Args> = ({ itemWeight, quantity }) => itemWeight * quantity;
// typeof calcTotalWeight === FN<Args, number> , or
// typeof calcTotalWeight === (Args) => number
I would like to type hint my function in TypeScript as below:
// would like to remove this type
type FN<TArgs, TReturn> = (args: TArgs) => TReturn;
interface Args {
itemWeight: number;
quantity: number;
}
const calcTotalWeight: FN<Args, number> = ({ itemWeight, quantity }) => itemWeight * quantity;
Is there any built-in generic that provides this utility? Currently, I have created one as above, but I feel as if this could be a very common use case. For example, react has FC
.
I do note that this type requires your function to be unary, but that's the whole point here. It's common to have a unary function, with the single argument an object so that we can have "named" parameters.
Does anyone know if this exists, or thoughts on whether this is a good idea?
Extension:
Does anyone know how to make the second argument of the generic optional so that it is inferred if not provided? For example:
const calcTotalWeight: FN<Args> = ({ itemWeight, quantity }) => itemWeight * quantity;
// typeof calcTotalWeight === FN<Args, number> , or
// typeof calcTotalWeight === (Args) => number
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论