Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript 对象的类型为';未知';类型脚本泛型_Typescript - Fatal编程技术网

Typescript 对象的类型为';未知';类型脚本泛型

Typescript 对象的类型为';未知';类型脚本泛型,typescript,Typescript,我有一个简单的函数,它以函数为参数,返回新函数。调用返回函数时,我得到的对象的类型为“未知” const makeFunction = <T>(callback: (someParam: number, options: T) => any) => { return (options: T) => { const param = 4; return callback(param, options) } } 为选项创建一个界面,或

我有一个简单的函数,它以函数为参数,返回新函数。调用返回函数时,我得到的
对象的类型为“未知”

const makeFunction = <T>(callback: (someParam: number, options: T) => any) => {

  return (options: T) => {
    const param = 4;

    return callback(param, options)  
  }  
}

为选项创建一个界面,或使用任何作为类型

makeFunction((param, options: any) => {

  const a = options.optionsValue;

  })({optionsValue: 'some value'});

Typescript将选项类型作为{},这会在编译过程中引起问题。

我们需要考虑TS如何从这个定义推断类型。TS可以从两个地方理解类型:

  • 显式泛型类型集
  • 函数的第二个参数的类型
在您的用例中,您在这些地方都没有提供类型,这就是为什么您会得到
unknown
,因为TS如何知道您需要的参数类型。为了使TS能够理解您可以执行的类型,或:

通过以下方式显式设置泛型:

makeFunction<YourType>((param, options) => {...))
您也可以通过内联方式说
((参数:number,选项:MyType))

如果
选项可以是动态的,请在评论后回答
我相信你想要以下行为:

const makeFunction = <F extends (someParam: number, options: any) => any>(callback: F) => {

  return (options: Parameters<F>[1]) => {
    const param = 4;

    return callback(param, options)  
  }  
}
const f = (a: number, b: {a: string}) => b
makeFunction(f)({ a: 'a' })
const g = (a: number, b: {b: number}) => b
makeFunction(g)({b: 1})
const makeFunction=any>(回调:F)=>{
返回(选项:参数[1])=>{
常数参数=4;
返回回调(参数,选项)
}  
}
常数f=(a:number,b:{a:string})=>b
makeFunction(f)({a:'a'})
常数g=(a:number,b:{b:number})=>b
makeFunction(g)({b:1})
我们只说几句话:

  • F
    现在是从二进制函数扩展而来的函数,我们直接推断它的类型
  • Parameters[1]
    是给定函数的第二个参数类型
    F
    type

向调用函数添加如下类型:

function():可观察的


为了避免它返回ig
unknown

谢谢你的回答,但是如果我想要选项作为动态类型呢?它的对象,但对象属性可能不同,这取决于它使用的位置
const f = (a: number, b: {a: string}) => b // here types are set
makeFunction(f)({a: 'some value'}) // makeFunction is able to infer the types by f
const makeFunction = <F extends (someParam: number, options: any) => any>(callback: F) => {

  return (options: Parameters<F>[1]) => {
    const param = 4;

    return callback(param, options)  
  }  
}
const f = (a: number, b: {a: string}) => b
makeFunction(f)({ a: 'a' })
const g = (a: number, b: {b: number}) => b
makeFunction(g)({b: 1})