typescript - Typescript: How type a function using generic type in this case?
问题描述
I have this type definition
type FuncType<T> = (value: T) => T
I want to implement a function using this type that would look like:
const myFunc: FuncType<T> = (value) => value;
and use it as follows:
const a: string = myFunc<string>('a');
const b: number = myFunc<number>(2);
But, of course, the previous line const myFunc: FuncType<T> = (value) => value;
doesn't have a valid syntax.
How should it be written ?
Note: I found a workaround using an intermediate function but it would be nice to avoid this useless currying (that I cannot use anyway in my real use case because it's related to react hook and react hooks doesn't tolerate currying):
const myFunc = <T>(): FuncType<T> => (value) => value;
const a: string = myFunc<string>()('a');
const b: number = myFunc<number>()(2);
Why do I need to use this type alias and cannot directly write ?
const myFunc = <T>(value: T): T => value;
Because in my real use case, the type definition of my function is not that simple.
It looks like something like that:
interface FuncType<T> {
(args: {arg1: T}): {res1: T}
(args: {arg1: T, arg2: T}): {res1: T, res2: T}
}
解决方案
So far I don't see a use case for FuncType
being a generic type alias to a concrete overloaded function. Could you instead make it a concrete type alias to a generic overloaded function? Like this:
interface FuncType {
<T>(args: { arg1: T }): { res1: T }
<T>(args: { arg1: T, arg2: T }): { res1: T, res2: T }
}
Then FuncType
will always refer to something that accepts any T
, and you can use it the way you wanted:
const myFunc: FuncType =
(value: { arg1: any, arg2?: any }) => ({ res1: value.arg1, res2: value.arg2 });
const a = myFunc<string>({ arg1: "" }); // { res1: string; }
const b = myFunc<number>({ arg1: 1, arg2: 2 }); // { res1: number; res2: number; }
Hopefully that meets your needs. Good luck!
推荐阅读
- vb.net - DotRas 错误“不支持转换值 'gre'。”
- c# - C# 中的多线程和更新表
- apache-spark - 将源文件存储在 Google dataproc HDFS 与谷歌云存储(谷歌存储桶)中
- java - 我怎样才能让我的复选框自己检查
- sql-server - 代码可以在一台计算机上运行 - 但不能在其他计算机上运行
- rest - 使用 POSTMAN 或任何其他方式批量 POST/PUT API 请求
- c# - 如何阻止 XmlSerializer 发出集合的空标记?
- tensorflow - TensorFlow 自动混合精度 fp16 比官方 resnet 上的 fp32 慢
- scope - 为什么在交互式 julia 会话中仍然失败本地/全局范围?
- excel - 如何访问工作表中的所有红色行?