In my code I make use of generics and Partial
. There is one case where I want to be sure that the Partial
object contains a specific property. This property is also a constraint for the generic type that is used by the method.
For me this is valid TypeScript code but the compiler complains:
Type '{ id: -1; } | ({ id: -1; } & Partial<T>)' is not assignable to type 'Partial<T>'.
Type '{ id: -1; }' is not assignable to type 'Partial<T>'.(2322)
Following the code and the example in TypeScript playground.
interface Unique { id: number };
class Foo<T extends Unique> {
bar(obj: Partial<T> | null): Partial<T> {
return { id: -1, ...obj};
}
}
Why the compiler complains? How would you refactor the code without casting?