To pinpoint the issue at hand, we must first analyze the data type being returned. The value
property shows the expected type:
{ valueType: string; value?: string | undefined; } | undefined;
Further examination of
input?.valueType ? input : undefined
reveals:
Partial<{
valueType: string;
value?: string | undefined;
}> | undefined
The problem lies in the mismatch - you specified that valueType
should be of type string
, but you attempted to assign it as string | undefined
due to the optional nature enforced by the Partial
helper.
The inferred Partial<T> | undefined
is a result of informing the compiler that the generate
function accepts Partial<MyType['value']>
as the second parameter. So, what can be done? Keeping the semantics intact, the most viable solution is to also make valueType
optional:
type MyType = {
greeting: string;
value?: {
valueType?: string;
value?: string;
};
};
function generate(name: string, input?: Partial<MyType['value']>): MyType {
const value = input?.valueType ? input : undefined;
return { greeting: `Hello, ${name}`, value }; //OK
}
This may not align with your objectives, but for achieving your desired outcome, utilizing optional chaining both as a type guard and to refine the Partial
type is necessary. This could be accomplished through a custom type guard like this one:
const withType = (val: Partial<MyType["value"]>) : val is Exclude<MyType["value"], undefined> => !!val?.valueType;
function generate(name: string, input?: Partial<MyType['value']>): MyType {
const value = withType(input) ? input : undefined;
return { greeting: `Hello, ${name}`, value }; //OK
}
Playground