I have a basic framework class:
export class BaseClass<
A extends boolean = false,
B extends boolean = false,
> {
readonly fieldA: A;
readonly fieldB: B;
constructor(options: {
readonly?: A,
many?: B
} = {}) {
// @ts-ignore
this.fieldA = options?.readonly || false;
// @ts-ignore
this.fieldB = options?.many || false;
}
public method1 = (data: any): any => { return }
public method2 = (data: any): any => { return }
}
When I inherit from it in a class without generics, everything works smoothly:
export class SubClass<
X extends boolean = false,
Y extends boolean = false,
> extends BaseClass<X, Y> {
method1 = (data: any) => new Date(data)
method2 = (data: any) => new Date(data).toISOString()
}
const instance = new SubClass({ many: true })
typeof instance.many // true
However, when I extend into a class with additional generic parameters, the assignment of BaseClass
generics does not function correctly and certain values default to their initial settings.
export class NewField<
P extends any = any,
Q extends boolean = false,
R extends boolean = false,
> extends BaseClass<Q, R>{
method1 = (data: any) => data as P
method2 = (data: any) => data as P
}
type P = "a" | "b" | "c"
const newObject = new NewField<P>({ many: true, readonly: true });
// Some tests for reassurance
assert<Equals<typeof newObject["readonly"], true>>() // Type 'false' does not meet the requirement 'true'
assert<Equals<typeof newObject["many"], true>>() // Type 'false' does not meet the requirement 'true'
Can you provide suggestions on how I can ensure that the extended NewField class returns the value based on its generic parameter P, while also correctly setting the readonly
and many
fields?