I'm currently working on a project where I have an object that needs to meet specific typing requirements. Here is the initial code snippet:
export const dateFormat = {
hourOnly: { hour: 'numeric' }
…
}
To ensure that the values in this object adhere to Intl.DateTimeFormatOptions
, I attempted the following modification:
export const dateFormat: {[key: string]: Intl.DateTimeFormatOptions} = {
hourOnly: { hour: 'numeric' }
…
}
While this adjustment achieved the desired outcome, it caused me to lose access to auto-complete functionality for this object elsewhere in the project. Adding as const
did not resolve this issue.
Is there a method to enforce the values of an object while retaining auto-complete for the keys?
I also experimented with the following approach:
type dateFormatOptions = 'hourOnly'
export const dateFormat: {[key: dateFormatOptions]: Intl.DateTimeFormatOptions} = {
hourOnly: { hour: 'numeric' }
…
}
Unfortunately, TypeScript alerted me that the index signature should be a string or a number in this scenario.