如何在不扩展类的情况下推断类属性类型

问题描述 投票:0回答:1
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 将类型推断为联合。 当我想推断类属性的类型时,每个键都被推断为类属性的所有可能类型。

typescript oop typescript-generics
1个回答
0
投票

您可以使用以下映射类型:

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;
© www.soinside.com 2019 - 2024. All rights reserved.