Typescript: Type of a property dependent on another property within the same object

I think what you are actually looking for is a discriminated union. IObject should itself be a union:

export type IObject = {
    type: "checked"
    parameters: IParametersCheck
} | {
    type: "counter"
    parameters: IParametersCounter
}
export type ObjectType = IObject['type'] //// in case you need this union
export type ObjectParameters = IObject['parameters']  //// in case you need this union

export interface IParametersCheck {
    checked: boolean
}
export interface IParametersCounter {
    max: number
    min: number
    step: number
}

You could also do it with conditional types but I think the union solution works better :

export interface IObject<T extends ObjectType> {
    type: T
    parameters: T extends 'checked' ? IParametersCheck: IParametersCounter
}

Or with a mapping interface:

export interface IObject<T extends ObjectType> {
    type: T
    parameters: ParameterMap[T]
}
type ParameterMap ={
    'checked': IParametersCheck
    'counter': IParametersCounter
}

export type ObjectType = keyof ParameterMap

Leave a Comment