Interactive
Revamped for a more thorough approach. The detailed explanations embedded in the code offer a clearer understanding, emphasizing the use of generics defined in class A and properties like public readonly i: _type_def_
to target specific key-value pairs. In Class C, you can now access this.i
or this.j
. You can also leverage the methods of the Object
constructor to deconstruct and reconstruct super.obj vs this.obj properties, with constant checks for object equality.
To directly access this.obj.i
, without using Object
constructor methods beforehand for deconstruction, additional advanced TS generics would need to be implemented. It is feasible to work with this.obj
through different approaches, one being:
// Accessing "i" key and its corresponding value
const iValue = Object.values(this.obj)[0].valueOf();
const iKey = Object.keys(this.obj)[0].toString();
// Reconstructing to achieve this.obj.i
const thisObjI = { [iKey]: iValue }
abstract class A<
T extends number extends { [index: string]: infer U } ? U : number
> {
obj;
constructor(obj: Record<string, T>) {
this.obj = obj;
}
// Inferred:
// constructor A<T extends number>(obj: Record<string, T>): A<T>
}
class B extends A<0> {
constructor(public readonly i: number extends infer U ? U : number) {
super({ i: 0 });
// Inferred:
// constructor A<0>(obj: Record<string, 0>): A<0>
}
stringify() {
return JSON.stringify(
{
i: this.i as number,
sup: super.obj as Record<string, 0>
},
null,
2
);
}
objValueOfCompare(valOne: number, valTwo: number) {
return valOne === valTwo ? true : false;
}
truthyCheck() {
const extractValueFromSuper = Object.values(super.obj)[0].valueOf();
const iIsValueOfObjRecord = <
T extends typeof this.i extends Record<string, infer U>
? U
: typeof this.i
>(
objectCompare: T
) => {
const extractThisInjectedObjectValue =
Object.values(objectCompare)[0].valueOf();
return this.objValueOfCompare(
extractValueFromSuper,
extractThisInjectedObjectValue
);
};
return iIsValueOfObjRecord; // Returns True
}
}
...