My goal is that foo accepts any object which extends an Obs<T>
. However I get the following error.
Argument of type '{ reset: () => number; x: number; set: (x: number) => number; }' is not assignable to parameter of type 'Obs<unknown>'.
Object literal may only specify known properties, and 'reset' does not exist in type 'Obs<unknown>'
Snippet A
{
// add a generic method
type Obs<T> = { x: T; set: (x: T) => T }
function createObs<T>(x: T): Obs<T> {
return { x, set: (val: T) => val }
}
function foo<O extends Obs<T>, T>(a: O) {}
const a = createObs(1)
foo({ ...a, reset: () => 1 }) // ❌ now throws the error
}
Interestingly if I remove the set
method the types work as expected like so.
Snippet B
{
type Obs<T> = { x: T }
function createObs<T>(x: T): Obs<T> {
return { x }
}
function foo<O extends Obs<T>, T>(a: O) {}
const a = createObs(1)
foo({ ...a, reset: () => 1 }) // ✅
}
How do I make Snippet A work with the generic set
method?