简体   繁体   English

TypeScript 函数参数类型推断不起作用

[英]TypeScript function parameter type inferring not working

According to TypeScript handbook , there is a type inferring in function type declaration.根据TypeScript 手册,在函数类型声明中有一个类型推断。 But when I introduce generic type into function declaration, the type inferring somehow not working.但是当我将泛型类型引入函数声明时,类型推断不知何故不起作用。 I have to explicitly write the type.我必须明确地写出类型。 Why the type inferring is not working when there is generic type?当有泛型类型时,为什么类型推断不起作用?

const fn1: (x: number, y: number) => number = (x, y) => {
  // working
  return x + y;
}
const fn2: <T>(x: number, y: number) => Promise<T> = <T>(x, y) => {
  // not working, although ws hints these parameters' type is number
  ...use type T somewhere...
  ...x + y;
  ...
}

error screen shot错误截图

Edit: Thank you for the comment.编辑:感谢您的评论。 But my question is different.但我的问题是不同的。

const fn1: (x: number, y: number) => number = (param1, param2) => {
  // typescript will infer the type of param1 and param2 is number
  return param1 + param2;
}
const fn2: <T>(x: number, y: number) => number = <T>(param3, param4) => {
  // I think typescript will infer the type of param3 and param4 is number
  // but with strict flag true (noImplicitAny), there is a compile error says param3 and param4 is type any
  // why adding generic type to function will cause type inferring not working?
  return param3 + param4;
}

Edit 2: Here is the actual code from the project编辑 2:这是项目的实际代码

type Request = <T>(method: Method, url: string, params?: Record<string, unknown>) => Promise<T>;
const request: Request = async <T>(
  // because I have declare the parameters type in type Request
  // why I have to declare the type again here for the parameters?
  // if I omit types here, typescript thinks these params are 'type any'
  method: Method, url: string, params: Record<string, unknown> = {},
) => {
  const fetchConfig: RequestInit = {
    method,
    credentials: 'same-origin',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
    },
  };
  let targetUrl = url;

  switch (method) {
    case Method.Get:
    case Method.Delete:
      targetUrl += qs.stringify(params, { addQueryPrefix: true, arrayFormat: 'comma' });
      break;
    case Method.Post:
      fetchConfig.body = JSON.stringify(params);
      break;
    default:
  }

  const resp = await fetch(targetUrl, fetchConfig);
  // I need to use generic type T here
  const respJson = await resp.json() as T;
  if (resp.status >= 200 && resp.status < 300) {
    return respJson;
  }
  if (resp.status === 401) {
    globalThis.history.replaceState(undefined, '', RouteURL.adminLogin);
  }
  const newError = new Error('Request failed');
  Object.assign(newError, { json: respJson });
  throw newError;
};

Syntactically, your problem is the <T> in <T>(x,y) after the = .语法上,您的问题是<T><T>(x,y)的后= You've already declared the type before the = as <T>(x: number, y: number) => Promise<T> .您已经在=之前将类型声明为<T>(x: number, y: number) => Promise<T> Everything to the right of the = is just an assignment so typing is not appropriate there. =右边的所有东西都只是一个赋值,所以在那里打字是不合适的。

What's a little less clear to me is what kind of inference you are hoping for.我不太清楚的是你希望得到什么样的推论。 Do you want the value in the promise to have the same type as the arguments?您是否希望承诺中的值与参数具有相同的类型? In that case you should type it as: <T>(x: T, y: T) => Promise<T>在这种情况下,您应该将其键入: <T>(x: T, y: T) => Promise<T>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM