#how can i have a class with a type dependent on another field?

6 messages · Page 1 of 1 (latest)

slate lark
#

I have something like this

class MySampleClass {
 type: MySampleType
 value: MySampleValue
}

Where MySampleType can be "number" or "string" and MySampleValue can be string or boolean, how can i infer one from another so the type of the value automaticly gets set?

crude frigate
#

sounds like you want generics

#

!hb generics

sour warrenBOT
crude frigate
#

for example:

#
type ValuesByTypeName = {
  string: string
  number: number // or boolean?
}
type TypeName = keyof ValuesByTypeName

class MySampleClass<T extends TypeName> {
  type: T
  value: ValuesByTypeName[T]
}