I’m trying to create a custom TypeScript type that only accepts field names whose types are related to a specific base class, WhateverBaseClass
.
How can I modify the MyType
definition to ensure it only includes the keys of MyClass
that correspond to fields of type WhateverBaseClass
or arrays of WhateverBaseClass
?
Here’s a simplified version of my code:
class WhateverBaseClass {}
class Invalid {
public invalidName!: string;
}
class Valid extends WhateverBaseClass {
public validName!: string;
}
class MyClass {
public name!: string; // Invalid: string
public validArray!: Valid[]; // Valid: array of Valid
public validField!: Valid; // Valid: instance of Valid
public invalidField!: Invalid[]; // Invalid: array of Invalid
}
type MyType<T> = {
[K in keyof T]: T[K] extends WhateverBaseClass | (WhateverBaseClass[]) ? T[K] : never;
}[keyof T];
// Expectation:
const expectation: MyType<MyClass>[] = ["validArray", "validField"]; // Must only accept these two
// Result:
const rs: MyType<MyClass>[] = ["validArray", "validField", "name", "invalidField"]; // But it accepts all