How do I determine if a class’s name exists as a key in a mapped object type?

  Kiến thức lập trình

I have a type that I’m trying to make dynamic. I currently have a hardcoded version that looks like this:

class Text {}
class TextOptions {}

export type ConstructorParams<T extends abstract new (...args: any) => any> =
  /**
   * We're adding a specific options type override for Text components because of the order of overloads.
   * @see https://github.com/pixijs/pixi-react/issues/500
   */
  T extends typeof Text
    ? TextOptions
    : never;

The goal is to return TextOptions if T matches typeof Text. That works fine, but now I want to be able to match multiple types here without writing a bunch of individual conditionals. This is what I’ve got so far (non-functional):

class BlurFilter {}
class BlurFilterOptions {}
class Text {}
class TextOptions {}

type ConstructorOverrides = {
  BlurFilter: BlurFilterOptions
  Text: TextOptions
}

export type ConstructorParams<T extends abstract new (...args: any) => any> =
  T extends keyof ConstructorOverrides
    ? ConstructorOverrides[T]
    : never;

This new type is to achieve the same as the original type, but based off of a dictionary. If T is Text, we should still return TextOptions, but if T is BlurFilter, we should return BlurFilterOptions.

Of course the second version doesn’t work because it’s checking if T matches a union type of the keys in ConstructorOverrides. I’ve been smashing my head on it all morning… how can I update this type to achieve my goals?

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT