繁体   English   中英

TypeScript:通用 function 类型参数是从错误参数推断的

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM