I look to fix the typing of the addRandomValue function, so that the Typescript compiler doesn't allow the below call, because baz is not in FooBar.
type WithRandomNumber<T> = T & { randomValue: number; };
function addRandomValue<T>(inputObj: T): WithRandomNumber<T> {
return {
...inputObj,
randomValue: Math.random(),
};
}
interface FooBar {
foo: string;
bar: number;
};
const resultObj: WithRandomNumber<FooBar> = addRandomValue({
foo: 'hello',
bar: 100,
baz: true,
});
That is, I want to constrain the generic T of addRandomValue (and hence the type of inputObj), so that if the expected return type is WithRandomNumber<Foobar> (because that's the variable type that we assign the return value to), then T has to equal FooBar.