How to pick props with a specific type?

Viewed 42

I need to have the implementation of such PropsWithType type:

type PropsWithType<TType, TProp> = ...

type Person = {
  firstname: string
  lastname: string
  age: number
}

const personName: PropsWithType<Person, string> = {
  firstName: 'Peter',
  lastName: 'Jackson',
}

const personAge: PropsWithType<Person, number> = {
  age: 20
}

This example is actually useless but this type will be used for generic factories, which will need to provide resolvers for props typed as object.

1 Answers

you can try like that:

export type FILTER_PROPS<Base, Condition> = {
    [Key in keyof Base]: Base[Key] extends Condition ? Key : never;
}[keyof Base]; // <- gets all keys of specified types.

type PropsWithType<TType, TProp> = Pick<TType, FILTER_PROPS<TType, TProp>>; // <- picks only specified keys.

type Person = {
  firstname: string
  lastname: string
  age: number
}

const personName: PropsWithType<Person, string> = {
  firstname: 'Peter',
  lastname: 'Jackson',
  random: '20', // <- isn't acceptable
}

const personAge: PropsWithType<Person, number> = {
  age: 20,
  random: 123, // <- isn't acceptable
  lastname: 'Jackson', // <- isn't acceptable
}
Related