Typescript Record value type based on Record key

102 views Asked by At

Using typescript, I would like to summarize different objects (based on different types) in one single Record while still maintaining type safety / correct IntelliSense.

For this demonstration example, I have the following types:

type Level = 'intro' | 'main' | 'outro';

type TypeA = {
    textA: string;
}

type TypeB = {
    textB: string;    
)

type TypeC = {
    textC: string;
)

I now would love to have some kind of Record like:

const record : Record<level,...> = {
    intro: contains Object of TypeA,
    main: contains Object of TypeB,
    outro: contains Object of TypeC
}

later, when i access this object, I would love to get IntelliSense support:

record.intro. (should now only suggest textA)
record.main. (should now only suggest textB)

I'd like to use a Record in my case because it enforces that I use all type values (intro, main, outro). Is there some way to accomplish this?

1

There are 1 answers

5
ouuan On
type Level = 'intro' | 'main' | 'outro';

interface LevelRecord {
    intro: TypeA;
    main: TypeB;
    outro: TypeC;
}

const _checkLevelRecord1: Record<Level, unknown> = {} as LevelRecord;
const _checkLevelRecord2: LevelRecord = {} as Record<Level, never>;