Hi there, I am trying to create a function that returns some interface and takes in an optional partial of the interface as its argument.
I would like the function's return type to reflect the partial passed in. For instance, in the following code, foo.b should be of type string, not string | null.
interface Foo {
a: string,
b: string | null
}
function genFoo(partial?: Partial<Foo>): Foo {
const foo= {
a: 'something random',
b: 'another random thing'
}
return {...foo, ...partial}
}
const foo = genFoo({b: 'not null'})
foo.b.toUpperCase() // Type error!
I tried the following but with no success.
interface Foo {
a: string,
b: string | null
}
function genFoo<T extends Partial<Foo>>(partial?: T): Foo & T {
const foo= {
a: 'something random',
b: 'another random thing'
}
return {...foo, ...partial} // Type error!
}
const foo = genFoo({b: 'not null'})
foo.b.toUpperCase()
It works if I make partial required, genFoo(partial:T), but how can I make it work while keeping partial optional?
I also experimented with function overloading and conditional return types, but things got complicated really quickly. I feel like I might be missing something obvious. I looked on SO and here and couldn't find any similar questions.
Any help would be greatly appreciated!
Playground link: