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 将类型推断为联合。 当我想推断类属性的类型时,每个键都被推断为类属性的所有可能类型。
您可以使用以下映射类型:
type ClassProps<T> = {
[K in keyof T]: T[K]
}
完整代码:
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]; // Direct assignment infers correct types
}
return returnObj;
}
const xObj = new XClass();
const schema = getSchema(xObj);
type X = typeof schema;