打字稿包装类型

奥斯卡·沃兹尼亚克

我有一些工厂方法可以进行一些计算和操作。我还有一个通用方法 doSomething。我不想每次都为 doSomething 指定类型。我想为工厂方法做一次,然后每次都用已经分配的类型来获取它

function factory<T>(t: T){
// some computations

return {method: doSomething<T>} <- this is what I wanna do
}

// Generic
function<T extends object>doSomething(): T{
//complex stuff, a lot of lambdas
}

如何从工厂方法中返回具有已分配类型的 doSomething?

杰卡兹

您不能在不调用它的情况下指定泛型函数的类型参数。所以doSomething<T>是不能接受的;doSomething<T>()允许。幸运的是,您可以只返回一个具体函数,该函数使用指定的正确类型参数调用泛型函数。像这样:

function factory<T extends object>(t: T) {
  // some computations
  return { method: ()=>doSomething<T>() } 
}

// Generic, note generic parameter comes after the function name
declare function doSomething<T extends object>(): T;

让我们看看它是否有效:

const ret = factory({a: "hey"}).method();
// const ret: { a: string }

在我看来很好。希望有所帮助;祝你好运!

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章