I have this code, which works just fine in a simple case, meaning the "permissionList" const is type inferred, VSCode can suggest me the properties, such as "permission_1". Also inside the "constraintFn", when I declare the object from which the type is inferred, it suggests me "code" and "id", since these are the valid properties that you can use based on the generic type "T".
type PropType<T> = {
[key: string]: T;
};
type Codes = 'code1' | 'code2';
class PermissionType {
code: string;
id: number;
}
const constraintFn = <T, TRe extends PropType<T>>(t: { new(): T; }, obj: TRe): TRe => {
return obj;
};
export const permissionList = constraintFn(PermissionType, ({
permission_1: {
code: 'code1',
id: 1,
},
permission_2: {
code: 'code2',
id: 2,
},
}));
Now, if I change one thing:
class PermissionType {
code: Codes; // this changed from string, to Codes
id: number;
}
The inference still works when I declare the object in the function param, I can chose from a list of Codes, BUT the inference of the const "permissionList" disappears, and it only displays:
PropType<PermissionType>
Instaead of:
{
permission_1: {
code: string;
id: number;
};
permission_2: {
code: string;
id: number;
};
}
Thanks, I hope there's a solution to this. It would be fun to create these kind of types.