Reputation: 5772
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
Reputation: 33051
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");
Upvotes: 2