Unit tests are necessary for validation. Here is an example:
type X = 1 | 2 | 3;
type Y = 4 | 5 | 6;
type Obj = {
x: X;
y: Y;
};
I am trying to achieve something like this:
const getObjTemplate = (overrideProperties: Partial<Obj>): Obj => ({
x: 1,
y: 4,
...overrideProperties,
});
describe('Test suite', () => {
const objs: Obj[] = [
{ x: 1 },
{ x: 2 },
{ x: 2 },
{ x: 3 },
].map(getObjTemplate);
test('...', () => {
// ...
});
});
An error message stating
Type 'number' is not assignable to type 'X | undefined'
pops up in regards to property x because it seems incompatible with the Partial<Obj>
. It could be that I am misusing Partial
or assuming too much about Typescript's inferencing capabilities, but I expected it to deduce the type of x and ensure any added properties fit the same type.
How can I specify that overriding properties must match the original types?
You can experiment on the Typescript playground here.