As part of a project, I have created two classes:
ParentClass
childrenClass
which extends theParentClass
class
Displayed below is the code for my ParentClass
:
interface ConfSetup<T extends boolean> {
enabled: T;
permissions: bigint[];
location: string;
}
interface AssistanceInfo {
name: string;
description: string
category: string;
id: number;
}
interface ParentClassConfiguration<T extends boolean> {
confData: ConfObj<T>;
assistance: HelpObj;
}
type ParentClassParameters<T extends boolean> = AssistanceInfo & ConfObj<T>;
class ParentClass<T extends boolean> {
config: ConfObj<T>;
assist: HelpObj;
constructor({ enabled, permissions, location, name, description, category, id }: ParentClassParameters<T>) {
this.config = {
enabled, permissions, location
};
this.assist = {
name, description, category, id
}
}
}
Following that, in the ParentClass
constructor, I set appropriate values to the class properties.
In the context of the childrenClass
, I extend the ParentClass
with necessary details. The goal is to modify the type of a parameter in the ChildrenClass
class when the value of ParentClass.conf.enabled
is true.
I attempted the following code (for the children class):
interface ChildConfigInterface<T extends ParentClass<any>> {
isEnabled: () => boolean;
name: string;
description: string | (T["conf"]["enabled"] extends false ? undefined : never);
}
class ChildrenClass extends ParentClass<true> {
constructor() {
super({
enabled: true,
permissions: [],
location: '',
name: '',
description: '',
category: '',
id: 0
});
}
operate(data: ChildConfigInterface<ChildrenClass>) {
return data.description;
}
}
So, in this scenario, if we set the ParentClass
value to true
, the type of data.description
should be string
. Conversely, if enabled is set to false
, then the type of data.description
will be string | undefined
.
I hope this explanation clarifies the concept. For further understanding, please refer to the provided minimal reproducible example on TS playground. The operate
method within the ChildrenClass
should execute error-free, without adding any conditional statements or altering the method's return type.