简体   繁体   中英

How to define the return type of a function according to the input parameters with Typescript?

I have a function with an object as argument:

// Types
type Params = {
  first: string;
  second: number;
  third?: boolean;
};
type FunctionA = (params: Params) => { [key: string]: any } | void;

// Function
const functionA: FunctionA = params => {
  // ... do something
  if (params.third) {
    return {one: "object"}
  }
};

So basically, what I want to achieve is that if third has been submitted, I want that the function return type is {[key: string]: any} . If third is not submitted, I want it to be never .

I have found solutions where the return type of a function changes according to the argument which has been returned but nothing, if the object is an argument and with a return type which is different from the argument type.

Is this even possible?

Thanks! Any help appreciated!

You could use function overloads .

LE: After reading the question better I think this is what you want:

type Params = {
  first: string;
  second: number;
  third?: boolean;
};

function A(params: Omit<Params, "third">): void
function A(params: Required<Params>): { [key: string]: any }
function A(params: Params): { [key: string]: any } | void {
  if (params.third === undefined) {
    return
  }

  return {...params}
}

Again, you are overloading the function, but this time you are declaring one without third in the params and another where all fields are required, including third .

You can see this in action in this playground .

You can declare 2 functions with 2 and 3 params and then implement it. Something similar to this:

function A (first: string, second: string, third: boolean): {[key: string]: any}
function A (first: string, second: string): never
function A (first: string, second: string, third?: boolean) {
  if (third === undefined) {
    throw new Error("error message")
  }

  return {first, second, third}
}

Now your IDE or any code helper should know that if you pass 2 params you have a return type and if you pass 3 another.

Note: I don't see a valid reason for returning never when not passing the third argument. Is almost like you want to make the 3rd one mandatory and not optional.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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