I'm trying to use the updeep
library. A typical example of using updeep
is something like this:
var person = {
name: {
first: 'Jane',
last: 'West'
}
};
var result = u({ name: { first: 'Susan' } }, person);
The idea here is that result
will be a clone of person
but with the value of name.first
changed. You can imagine this function, u
, defined in TypeScript as:
function u<T>(changes: {}, obj: T): T { ... }
This captures the fact that the type of the second argument is also the return type of the function. But what it does not express is that changes
should be a super type of T
.
What I'd like is some type checking on the first argument. The point is that the values present in the changes
arguement should all be present in the T
type parameter and match the types of their counterparts there. Expressing this allows us to check the changes
argument to make sure it makes sense with respect to the type T
(i.e., is a super type of T
).
I'm not sure if this is possible in TypeScript. In languages like Java, you have the super
keyword and it can be used to describe constraints on type parameters.
While TypeScript doesn't allow it, something like this expresses what I would like:
function u<T extends U,U extends {}>(changes: U, obj: T): T { ... }
Does anybody have an suggestions on how to express this? It would be great to have a typesafe system for performing such transformations.
Thanks.
T
: anyT
(which has all the keys) is assignable to the partial type (where the keys are optional). It's not quite every supertype, since each key's type has to be either the same as it was inT
or not present at all.