Given:
const qualities = ["beauty", "cost", "upkeep"] as const
export type QualityStrings = (typeof qualities)[number]
I make use of QualityStrings outside, it cannot be discarded.
I also need an interface like the following:
export interface QualitiesInterface {
beauty: number
cost: number
upkeep: number
}
as I’m implementing and extending the interface elsewhere.
But this is not DRY, I’m repeating myself. Would it be possible to define the same interface with mapped types?
export interface QualitiesInterface {
[???]: number
}
I can define those keys dynamically in a type but don’t know how to do the same for an interface:
type QualitiesType = {
[V in QualityStrings]: number
}
>Solution :
What you need is Record<..., ...> I believe.
So, in this case it could be rewritten as:
export interface QualitiesInterface extends Record<QualityStrings, number> {}
Basically we’re ‘converting’ type to interface above with the use of extension semantics:
interface SomeThing extends MyType {
// normal iface stuff can be added here if needed
}