I need a function, that alters a specific variable in my Object:
function updateField(fieldname, newValue){
return {...this.oldObject, fieldname: newValue};
}
And I want to make it Typesafe. Type of fieldName is typeof clazz, but what is the Type of newValue?
I know Typescripts Pick, so full typing would be something like:
updateField(fieldname: typeof Clazz, newValue: Pick<Clazz, fieldname>): Clazz
but I don't know how to go with non-constant strings. Is that even possible in TS?
You can restrict a filed name to be a valid object key using
keyofoperator. To get a type of value you can use lookup typeT[K]whereTis the object type andKis the key type:Playground