[英]TypeScript: generic function type argument is inferred from a wrong parameter
在下面的代码中,如果我没有在 function 调用中明确指定T
,例如getOrPut<Item>(...)
,它是从create
参数推断出来的,因此创建的项目类型可能与obj
字典不兼容,有关示例,请参见代码的最后一行。
function getOrPut<T>(
obj: { [key: string]: T | undefined },
key: string,
create: () => T
): T {
const value = obj[key];
if (value) {
return value;
} else {
return obj[key] = create();
}
};
type Item = { title: string };
type Dictionary = { [key: string]: Item };
const dictionary: Dictionary = {};
// the foo type is {} but I expect Item
const foo = getOrPut(dictionary, 'foo', () => ({}));
是否可以强制从obj
参数推断T
?
它确实有效,您必须在create
参数中传递一个Item
。
function getOrPut<T>(
obj: { [key: string]: T | undefined },
key: string,
create: () => T
): T {
const value = obj[key];
if (value) {
return value;
} else {
return obj[key] = create();
}
};
type Item = { title: string };
type Dictionary = { [key: string]: Item }
const dictionary: Dictionary = {};
// the foo type is {} but I expect Item{
const foo = getOrPut(dictionary, 'foo', () => ({} as Item)); // <--- casting here
我通过根据obj
类型指定create
返回类型找到了一种解决方法:
function getOrPut<T>(
obj: { [key: string]: T | undefined },
key: string,
create: () => NonNullable<typeof obj[string]>
): T { ... }
不幸的是,由于某种原因,该解决方案仅适用于 TypeScript 3.6.3
而我当前的版本是3.5.3
,但它应该很快更新。 我不确定这是最好的解决方案,也许有更好的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.