Say I have this:
type TypeMapping = {
Boolean: boolean,
String: string,
Number: number,
ArrayOfString: Array<string>,
ArrayOfBoolean: Array<boolean>
}
export interface ElemType {
foo: keyof TypeMapping,
default: valueof TypeMapping
}
instead of using any
for default, I want to conditionally define it, I tried this:
export interface ElemType<T extends TypeMapping> {
foo: keyof T,
default: T
}
but that doesn't seem quite right, does anyone know the right way to do this?
if it's not clear, for any given object that has type ElemType, the key that foo points to, must be matched by the value that foo points to. For example, this is valid:
{
foo: 'String',
default: 'this is a string'
}
but this is not:
{
foo: 'Boolean',
default: 'this should be a boolean instead'
}
so the type of the default field is conditional on the value/type of the type field.
Succintly, if foo
is 'ArrayOfBoolean'
, then default
should be: Array<boolean>
. If foo
is 'Number'
, then default should be number
, if foo is 'Boolean'
then default should be boolean
, etc etc.