I am working on creating a specific type that guarantees all fields listed in the requiredFields
array are included in the defaults
object.
The goal is to have defaults
trigger type errors if any of the names from requiredFields
are missing, and if the values do not match the specified options
.
The requiredFields
array should be adaptable. While the entire object will be known statically and not assessed at runtime, I want to set up various versions with the same type logic to ensure no omissions in registering defaults
.
const configuration: FormConfiguration = {
defaults: { // should throw error for missing `numbers`
letters: 'f', // should throw error because 'f' is not an option
},
requiredFields: [
{
name: 'letters',
options: ['a', 'b', 'c'],
},
{
name: 'numbers',
options: [1, 2, 3],
},
],
}
While there are other methods to define defaults for form items, this example serves as a model for a more intricate type that I am striving to build.
This is my current approach to defining types:
type Names = FormConfiguration['requiredFields'][number]['name']
// returns:
// type Names = string
type Options =
FormConfiguration['requiredFields'][number]['options'][number]
// returns:
// type Options = string | number
type FormConfiguration = {
requiredFields: Array<{
name: string
options: (string | number)[]
}>
defaults: Record<Names, Options>
}
Based on the results, it appears there is no self-referencing or correct per-item options retrieval happening.
There must be a way to achieve this, right?