Aarti Prabhu
Aarti Prabhu

Reputation: 50

Is it possible to dynamically set flow type of a function in an object to the type of one of its properties?

Consider a config of type:

type Config = {
  props: any,
  isEnabled?: (args: { custom: string, props: any }) => boolean,
};

I want to use this Config type such that any changes to it will apply to all its subtypes. I am able to do this as:

type ConfigAProps = {
  propA: boolean
}

type ConfigBProps = {|
  propsB: string
|}

type ConfigA = {|
  ...Config,
  props: ConfigAProps
|}

type ConfigB = {|
  ...Config,
  props: ConfigBProps
|}

Now the isEnabled in type Config still has argument of props:any. Is there a way to specify that the type of props in isEnabled is the same type as props field in the object (sort of like this.props)? Or is there a better way to model these types?

Upvotes: 0

Views: 174

Answers (1)

loremdipso
loremdipso

Reputation: 389

I think you want to use generics here. Instead of splatting Config, instead do:

type Config<T> = {
  props: T,
  isEnabled?: (args: { custom: string, props: T }) => boolean,
};

type ConfigA = Config<ConfigAProps>;

Upvotes: 1

Related Questions