目前,我能够得到键值的联合,每个对象文本的值被传递到一个函数中。
例如:
interface StaticClass<T = any> {
new (...args: any[]): T
}
type RecordOfStaticClasses = Record<string, StaticClass>;
type RecordOfInstances<T extends RecordOfStaticClasses> = Record<keyof T, InstanceType<T[keyof T]>>;
const transformObjLiteral = <T extends RecordOfStaticClasses>(input: T): RecordOfInstances<T> => {
return Object.fromEntries(Object.entries(input).map(([key, value]) => [key, new value])) as RecordOfInstances<T>;
}
// Transformation
class Cat {
asleep: boolean;
}
class Zebra {
hoofLength: number;
}
transformObjLiteral({ myCat: Cat }).myCat.asleep // works if only 1 key is added
transformObjLiteral({ myCat: Cat, myZebra: Zebra }).myCat.asleep // Error: Property 'asleep' does not exist on type 'Cat | Zebra'!从上面可以看出,当只传递带有1键的对象文本时,它工作得很好。但是,当添加两个键时,由于可能存在Union类型,因此无法获得特定的结果。我知道我可以使用泛型(例如transformObjLiteral<{ myCat: Cat }>({ myCat: Cat })),但我希望通过它本身就能隐式地实现这一点。这个可以定位吗?
https://stackoverflow.com/questions/73710125
复制相似问题