Let's say I have a function
function addField(obj, name, value) {
return { ...obj, [name]: value }
}
How do I type it in Typescript? EDIT: I'm having trouble with the return type. I'd like it to be "the original T
but with this one [name]
property in it".
I hoped this could work, but unfortunately it doesn't:
function addField<T, V>(obj: T, name: string, value: V): T & { `${name}`: V } {
return { ...obj, [name]: value }
}
(it complains that name
is a value and not a type). So, a kind of hack that works is
// Hope that nameVal has only one key
function addField<T, V, N extends { [K: string]: V }>(
obj: T,
nameVal: N
): T & { [K in keyof N]: V } {
return { ...obj, ...nameVal };
}
But this still isn't 100% what I want (as it allows for multiple fields being added), and it's not really nice either. Is there a better way to dynamically add fields to an object and codify it into the type systen?
EDIT2: I guess I could use this to disallow objects with more than one key, but I'd like to keep the original addField(obj, name, value)
anyway.