damusix
damusix

Reputation: 131

How to map a new type with the keys of the value types of another type?

I'm trying to make a type from the type-values of another type but I get these weird edge cases....

Here's a link to the playground

What I'm trying to do:

Let's say I have a filter criteria where I want to say: "If I am filtering by value X, when the value is Y, set it to true, when the value is Z, set it to false":

type KeyValsAsType<
    Criteria, 
    K extends keyof Criteria
> = Criteria[K] extends string ? (
    Partial<Record<Criteria[K], string>>
) : never;

This would allow me to deduce that, given the following type:

type FilterA = {

  nodeEnv: 'prod' | 'stage' | 'dev',
}

I should be able to create a new type:


type MyFilter = KeyValsAsType<FilterA, keyof FilterA>;

Which should mean that the following is a valid type:


const X: MyFilter = {
    prod: true,
    stage: false,
    dev: false
}

If I were to add another key, it would populate those values as well, which is acceptable, however, if I were to add a { key: string }, the extends type check jumps to the never clause

type FilterA = {

  nodeEnv: 'prod' | 'stage' | 'dev', // populates if its by itself
  appEnv: 'local' | 'qa' | 'live', // also populates these values,
  email: string, // destroys the generic logic
}

Any ideas on how I can filter out keys that are non-specific? Or am I approaching this the wrong way?

Upvotes: 1

Views: 380

Answers (0)

Related Questions