假设我有一个像这样的工厂:
const factories = {
foo: () => 'some string',
bar: () => 123,
};我想使用这个对象来键入一个类属性。这个类的目标是拥有一个具有与上面相同的键的属性,但是使用时,工厂的返回类型是,而不是工厂本身。
class MyClass {
myItems: ???; // What type here to have the below working?
}
const instance = new MyClass();
instance.myItems.foo; // Should be a string, not a function
instance.myItems.bar; // Should be a number, not a function简而言之,我不希望这样做:
class MyClass {
myItems: typeof factories;
}但如下所示:
class MyClass {
myItems: Record<keyof typeof factories, ReturnType<typeof factories>>;
}但当然,如果出现此错误,上述操作将不起作用:
TS2344:键入'{ foo:() =>字符串;bar:() =>数字;}‘不满足约束'(...args: any) => any’。另一种类型是'{ foo:() =>字符串;bar:() =>数字;}‘不提供签名的匹配“(...args: any):any’。
你有什么帮助吗?
提前感谢!
发布于 2021-06-14 14:04:35
你可以这样做:
const factories = {
foo: () => 'some string',
bar: () => 123,
};
type Factory<T> = () => T;
type FactoryValues<T> = {
[K in keyof T]: T[K] extends Factory<infer U> ? U : never;
};
const values: FactoryValues<typeof factories> = {
foo: 'test',
bar: 123,
};https://stackoverflow.com/questions/67971455
复制相似问题