How to resolve TypeScript error ts(2536) when indexing class instance in a generic testing function?

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

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật