最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Typescript return type based on function - Stack Overflow

programmeradmin1浏览0评论

Is there a way to avoid to duplicate the <number> and <string> fn1 and fn2 signatures when calling the generic function?

interface Result<T> {
  data: T
}

type ActionResponse<T> = Result<T>;

function fn1(): ActionResponse<number> {
  return {
    data: 1,
  };
}

function fn2(): ActionResponse<string> {
  return {
    data: '1',
  };  
}

function generic<T>(fn: () => ActionResponse<T>): T {
  const response = fn();
  return response.data;
}

const res1 = generic<number>(fn1);
const res2 = generic<string>(fn2);

Is there a way to avoid to duplicate the <number> and <string> fn1 and fn2 signatures when calling the generic function?

interface Result<T> {
  data: T
}

type ActionResponse<T> = Result<T>;

function fn1(): ActionResponse<number> {
  return {
    data: 1,
  };
}

function fn2(): ActionResponse<string> {
  return {
    data: '1',
  };  
}

function generic<T>(fn: () => ActionResponse<T>): T {
  const response = fn();
  return response.data;
}

const res1 = generic<number>(fn1);
const res2 = generic<string>(fn2);
Share Improve this question asked Feb 1 at 22:04 njordnjord 1,28812 silver badges25 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 2

You can simply omit the type parameter and allow it to be inferred:

const res1 = generic(fn1);
const res2 = generic(fn2);

See a full example at https://tsplay.dev/WYpAdm


Type inference is explained in the documentation on Generics:

Once we’ve written the generic identity function, we can call it in one of two ways. The first way is to pass all of the arguments, including the type argument, to the function:

let output = identity<string>("myString");

Here we explicitly set Type to be string as one of the arguments to the function call, denoted using the <> around the arguments rather than ().

The second way is also perhaps the most common. Here we use type argument inference — that is, we want the compiler to set the value of Type for us automatically based on the type of the argument we pass in:

let output = identity("myString");

Notice that we didn’t have to explicitly pass the type in the angle brackets (<>); the compiler just looked at the value "myString", and set Type to its type. While type argument inference can be a helpful tool to keep code shorter and more readable, you may need to explicitly pass in the type arguments as we did in the previous example when the compiler fails to infer the type, as may happen in more complex examples.

发布评论

评论列表(0)

  1. 暂无评论