I have the following function:
const fieldDefinitions = {
a: { id: "14", "default": "none" },
b: { id: "15", "default": 0 },
c: { id: "16", "default": 0 },
};
const setFields = <T extends typeof fieldDefinitions, K extends keyof T>(fieldValues: { fieldName: K, value: T[K]["default"] }[]) => {
//logic to set fields
}
I want to type it in a way that it will only accept field values that are of the same type as the default value.
E.g.:
setFields([
{ fieldName: "a", value: "somestring" },
{ fieldName: "c", value: 123 },
])
//should work because:
// - default of a is "none" which is a string
// - default of c is 0 which is a number
setFields([
{ fieldName: "a", value: 123 },
{ fieldName: "c", value: "somestring" },
])
//should NOT work because:
// - default of a is "none" which is a string, but a number is given
// - default of c is 0 which is a number, but a string is given
Here is where I get the error in the typedefinition:
value: T[K]["default"]
It says: Type '"default"' cannot be used to index type 'T[K]'
So my question is, what is the right way to access the type of the "default" property of T[K] here?
Here is the code in TypeScript Playground: