Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Define interface based on array type

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading