NomCereal
NomCereal

Reputation: 113

Typescript - creating a type where the keys come from a pre-existing type - but not required

Title might be a bit confusing, so let's try and explain better.

Say I have a type called Stage.

type Stage = 'beta' | 'gamma' | 'prod';

I want to create a new type where the keys can only be from Stage - but I don't want to require all possible keys of Stage to be keys on the created object.

For example, something like this would be fine:

const obj: NewVal = {
    beta: value,
    prod: value2,
};

I have tried using the following:

type NewVal = Record<Stage, string>;

type NewVal = { [key in Stage]: string };

but both of those options require all keys of Stage to be present on the object. Using Partial seems to work, but it introduces more issues when dealing with possible undefined values, so I'd rather not deal with it.

Is there some way to accomplish what I'm trying to do?

Upvotes: 0

Views: 67

Answers (1)

Michael Lorton
Michael Lorton

Reputation: 44386

Would

type NewVal = { [key in Stage]?: string };

address your issues? Or is that too close to Partial?

Upvotes: 1

Related Questions