For example:
interface U {
u: boolean;
}
const f = <T extends U>() => {
const t: Partial<T> = {u: true};
};
I get the following error:
Type '{ u: true; }' is not assignable to type 'Partial<T>'.ts(2322)
Playground link
Is there a way to fix this without casting to any?
The issue, that TypeScript complains about is the following:
Type '{ u: true; }' is not assignable to type 'Partial<T>'.ts(2322)
your function f
could be called with:
f<{ u: boolean, v: boolean }>(); // ok since U is "implemented" but not "v"
this opens the option, that your generic and your provided concrete implementation of an object inside the function { u: true }
could differ.
The TypeScript compiler doesn't enforce you to define the same type as it extends, you are still able to specify a more specific implementation of U as long as U is fully provided (in this case the boolean flag u
).
interface U {
u: boolean;
}
const f = <T extends U>() => {
const t: Partial<T> = {u: true} as Partial<T>;
};
f<U>();
Downside: { u: true }
could well be replaced with: { v: true }
which can cause issues with undefined later on in your code.
To tell the compiler to exactly use type U
, you could, if possible, try to re-phrase the function and move the constant t
as a function parameter.
interface U {
u: boolean;
}
const f = <T>(u: T) => {
const t: Partial<T> = u;
};
f<{ u: boolean }>({ u: true });
Your function requires a generic type but your function body assigns a concrete type which causes the trouble here. You could consider if generics are relevant there. A generic free alternative would be:
interface U {
u: boolean;
}
const f = () => {
const t: Partial<U> = {u: true};
};
f();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With