user3612643
user3612643

Reputation: 5772

Inference of function return type based on parameters

Consider this example:

export function foo(foo?: string) {
  return foo ? { foo } : {};
}

const F1 = foo();
const F2 = foo("y");

The compiler infers both types of F1 and F2 to be:

{
    foo: string;
} | {
    foo?: never;
}

Is it somehow possible to convince the compiler to infer F1 to {foo:string} and F2 to {}?

Upvotes: 1

Views: 34

Answers (1)

You need to overload your function:

function foo(): {}
function foo<S extends string>(foo: S): { foo: S }
function foo<S extends string>(foo?: S) {
  return foo ? { foo } : {};
}

const F1 = foo();
const F2 = foo("y");

Playground

Upvotes: 2

Related Questions