I’m having difficulty resolving a TypeScript type error ts(2536)
.
For context, I have classes that store configuration values for various components.
One such component is the AWSConfig
class below.
class AWSConfig {
readonly accessKeyID: string;
readonly secretAccessKey: string;
readonly region: string;
constructor() {
// ... code to validate environment variables
// assign validated variables to the respective properties
this.accessKeyID = '...';
this.secretAccessKey = '...';
this.region = '...';
}
// ... other methods
}
The logic for unit testing these config classes is similar, differing in the test cases.
I’m writing a generalized testing function that can be used to test these classes for the rest of my team.
There is a type error that I’m unable to resolve properly in the generalized testing function.
The function signature is as follows.
function configTests<
T extends ConfigClass<T>,
P extends ClassProperties<T> = ClassProperties<T>,
>(
Config: T,
cases: ReadonlyArray<ConfigTestCases<P>>,
) {
// ... simplified code for brevity
cases.forEach(({ property, tests }) => {
const config = new Config();
tests.forEach(({ expected }) => {
const result = config[property] === expected;
console.log(result);
});
});
}
This enables tests to be written as follows.
configTests(
AWSConfig,
[
{
property: 'accessKeyID',
tests: [
{
expected: '...',
},
// ... other cases
],
},
// ... other properties
],
);
Within the configTests
function, the lines that cause the error are as follows.
const config = new Config();
const result = config[property] === expected; // ts(2536) error at config[property]
The error occurs at config[property]
as Type 'Extract<keyof P, string>' cannot be used to index type 'InstanceType<T>'.ts(2536)
.
I removed the error using const config = new Config() as Record<string, unknown>
.
I think the types are not entirely correct but I’m out of ideas on how to address that.
The complete code is available at the TypeScript Playground here.
6
The code in the example is more complex than required for this to work. In particular,
interface ConfigClass<T extends ConfigClass<T>> {
new(): InstanceType<T>;
}
is a recursively bounded generic type. While there are situations where such types are useful, here it only looks like you’re trying to say that a ConfigClass<T>
is a construct signature that constructs instances of the instance type that ConfligClass<T>
constructs. That’s going to be true of any constructor type, and all the T
constraint does is make things more difficult on the compiler. You can replace this with just new () => object
for all the good it does. Indeed I don’t think you need a named type at all for this.
Instead of making things generic in the constructor type, let’s rewrite your code to be generic in just the instance type. All your uses of the constructor type have been to just go back to the instance type via the InstanceType<T>
utility type. That’s a conditional type, and when T
is generic, TypeScript doesn’t know how to analyze it. While a human being can understand what InstanceType<T>
for arbitrary T
(especially given the name of the type), TypeScript only “understands” it when T
is some specific type. It can’t abstract over the operation to “see” what happens in general. So in such situations you’ll tend to get errors where TypeScript cannot verify compatibility.
So let’s make things generic in the instance type. In ClassProperties<T>
, T
will just be the instance type itself and thus simplifies to:
type ClassProperties<T> = {
[K in keyof T as T[K] extends Function ? never : K]: T[K];
};
(and note, your AnyFunction
type really isn’t any function, since you made the rest parameter unknown[]
, which is restrictive, not permissive. See TypeScript `unknown` doesn’t allow non-unknown types in function parameters. If you want to actually exclude functions, you can just use the Function
interface, which is a bad thing to use for typing actual variables, but when checking for the existence of a call signature it’s ideal.)
And in configTests
you can use T
as the instance type. And importantly, you don’t need a separate generic P
, since you can just use the expected type directly:
function configTests<T extends object>(
Config: new () => T,
cases: ReadonlyArray<ConfigTestCases<keyof ClassProperties<T>>>,
) {
cases.forEach(({ property, tests }) => {
const config = new Config();
tests.forEach(({ expected }) => {
const result = config[property] === expected;
console.log(result);
});
});
}
This compiles. TypeScript understands that keyof ClassProperties<T>
is a assignable to keyof T
, which is all you really needed for this to start working. TypeScript does not have to try to analyze InstanceType<T>
, and even more importantly, it doesn’t have to try to understand how/if P
relates to T
. In your code, P
just defaulted to ClassProperties<T>
, and was constrained to ClassProperties<T>
, but that doesn’t mean it is identical to ClassProperties<T>
. It can be any subtype, like ClassProperties<T> & {someRandomProp: string}
. And that possibility means that TypeScript really cannot be sure that property
is a key of config
. Your code, as-is, allows this:
configTests<typeof AWSConfig,
{
accessKeyID: string,
secretAccessKey: string,
region: string,
someRandomProperty: string
}>(AWSConfig,
[
{
property: 'someRandomProperty',
tests: [
{
expected: '...',
},
],
},
],
);
And there’s no reason to allow that. Having an extra generic type parameter makes things worse.
Okay, so let’s test it:
configTests(
AWSConfig,
[
{
property: 'accessKeyID',
tests: [
{
expected: '...',
},
],
},
],
);
That still works, and if you inspect the call, you’ll see that T
has been inferred as AWSConfig
. You can’t put someRandomProperty
in there, as there’s no second type argument. So you’ll get an error if you try, either because someRandomProperty
is not in keyof T
, or because the AWSConfig
constructor doesn’t make instances that have someRandomProperty
:
configTests<AWSConfig & { someRandomProperty: string }>(
AWSConfig, // error here!
[
{
property: 'someRandomProperty',
tests: [
{
expected: '...',
},
],
},
],
);
Playground link to code
1