【发布时间】:2022-01-02 11:37:13
【问题描述】:
我可以像这样定义和使用通用函数:
const fetchData = <T>(): T[] => {
const arr: T[] = []
// if stuff push to arr
return arr
}
const emptyStringArray = fetchData<string>();
但是,在我的实际场景中,我有很多参数,并且想将类型和函数分配分开。
我尝试过这样写:
type IFetchData = <T>() => T[]
const fetchData2: IFetchData = () => {
const arr: T[] = []
// if stuff push to arr
return arr
}
const emptyStringArray = fetchData2<string>();
但是,现在函数定义无法将 T 识别为可用类型。
找不到名称“T”。
我已经尝试了很多不同的配置来放置<T>,但似乎没有任何效果 - 有什么想法吗?
Demo in TS Playground
相关问题
【问题讨论】:
标签: typescript typescript-generics