Issue
class XClass {
x = "x";
y = 11;
b = true;
}
let xObj = new XClass();
function getSchema<T extends XClass>(instance: T): Record<keyof T, T[keyof T]> {
const returnObj = {} as Record<keyof T, T[keyof T]>;
for (const key in instance) {
returnObj[key] = instance[key]; // Direct assignment infers correct types
}
return returnObj;
}
let schema = getSchema(xObj);
type X = typeof schema;
/* type being inferred as
type X = {
x: string | number | boolean;
y: string | number | boolean;
b: string | number | boolean;
}
// It should be instead :
type X = {
x: string;
y: number;
b: boolean;
}
*/
Typescript is inferring the types as a union. When i want to infer type of class properties each key is being inferred as all the possible types of the class properties.
Solution
You can use the following mapped type:
type ClassProps<T> = {
[K in keyof T]: T[K]
}
Full code:
class XClass {
x = "x";
y = 11;
b = true;
}
type ClassProps<T> = {
[K in keyof T]: T[K]
}
function getSchema<T extends XClass>(instance: T): ClassProps<T> {
const returnObj = {} as ClassProps<T>;
for (const key in instance) {
returnObj[key] = instance[key];
}
return returnObj;
}
const xObj = new XClass();
const schema = getSchema(xObj);
type X = typeof schema;
// type X = {
// x: string;
// y: number;
// b: boolean;
// }
Answered By - Lesiak
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.