I have the following
export type WithRequired<T, K extends keyof T> = T & { [P in K]-?: T[P] };
type A = {
f1?: string;
};
function test(a: A): WithRequired<A, 'f1'> {
if (a.f1) {
return a;
} else {
throw Error();
}
}
however, this gives an error
Type 'A' is not assignable to type 'WithRequired<A, "f1">'.
Type 'A' is not assignable to type '{ f1: string; }'.
Types of property 'f1' are incompatible.
Type 'string | undefined' is not assignable to type 'string'.
Type 'undefined' is not assignable to type 'string'.
I guess I would have expected this to work, since in the context of this branch, the compiler knows that a.f1 is not undefined….and in some contexts, typescript will do this correctly.
I guess I have two questions
- why doesn’t this work? (to understand the compiler better)
- is there a way to make something like this work without a cast?