Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I assign a U to a Partial<T> when T extends U? [duplicate]

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?

like image 208
btmorex Avatar asked Nov 06 '22 09:11

btmorex


1 Answers

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).

A few possible solutions are:

Use Type-Cast (as used before):

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.

Try to re-phrase your function

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 });

Consider if generics are relevant

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();
like image 88
r3dst0rm Avatar answered Nov 15 '22 10:11

r3dst0rm