Typescript interface extends same interface multiple times

75 Views Asked by At

I have the following situation: I have type with the following definition:

type A<year extends number> = `a${year}`

And I want to have an interface or a type such that, it has a variable amount of A<year> as keys as required properties and some other properties. For example:

interface AStatistics<years extends number[]>
extends Record<A<year0> & A<year1> ..., number>
& {
    aCommonProp: string
}

How can this be achieved?

1

There are 1 best solutions below

2
colinD On BEST ANSWER

I don't know if you can achieve it with interface, but you can use indexed access types like this:

type A<year extends number> = `a${year}`;

type AStatistics<TYears extends number[]> = { [K in A<TYears[number]>]: number } & { aCommonProp: string };

const stats: AStatistics<[1990, 1991, 2002]> = {
    a1990: 1,
    a1991: 2,
    a2002: 123,
    aCommonProp: "some prop"
}

Link to playground.