I am trying to generalise a service layer in an API in typescript using a base Data Transfer Object.
To not have to re-write the types definition i'm using <Omit>.
However, it raises some typescript errors that i am not able to understand.
For instance, i do not understand why the following code:
type A = { a: string };
function test<T extends A>(ot: Omit<T, "a">): T {
return {
...ot,
a: "a",
};
}
is raising the following error:
Type 'Pick<T, Exclude<keyof T, "a">> & { a: string; }' is not assignable to type 'T'. 'Pick<T, Exclude<keyof T, "a">> & { a: string; }' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'A'.
I understand why
function test<T extends string>():T {return "This is not specific enough!"}
does not work, but in the case above we are just defining dynamically the omitted field, we are not forgetting any constraint. What am i getting wrong?
class BaseService<Model> { function create(o: <Omit Model, "id">): Modelnow... maybe i could define myModelwithout the id everywhere and use your trick for all of the functions. It's just counter-intuitive - A. Laurent