Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
ReSharper:Typescript错误返回类型不相关_Typescript_Resharper - Fatal编程技术网

ReSharper:Typescript错误返回类型不相关

ReSharper:Typescript错误返回类型不相关,typescript,resharper,Typescript,Resharper,我明白了 返回类型不相关 重载签名与函数定义不兼容:Return 类型不相关 此文件中的ReSharper插件出错 public getCache<T>(key: string): T; public getCache<T>(key: string, defaultValue: T): T; public getCache<T>(key: string, defaultValue?: T): T { const result = localStorag

我明白了 返回类型不相关

重载签名与函数定义不兼容:Return 类型不相关

此文件中的ReSharper插件出错

public getCache<T>(key: string): T;
public getCache<T>(key: string, defaultValue: T): T;
public getCache<T>(key: string, defaultValue?: T): T
{
    const result = localStorage.getItem(key);
    return result ? JSON.parse(result) as T : defaultValue;
}
打字脚本代码

我明白为什么了。第一个重载中的泛型参数T与第二个重载中的T没有任何共同之处。我可以写

public getCache<T1>(key: string): T1;
public getCache<T2>(key: string, defaultValue: T2): T2;
public getCache<T>(key: string, defaultValue?: T): T
{
    const result = localStorage.getItem(key);
    return result ? JSON.parse(result) as T : defaultValue;
}
这个问题有解决办法吗? 我的ReSharper版本是2017.3 15.5.27130.2024


由于TypeScript具有可选参数,因此在这种情况下重载没有意义。只需使用最后一个签名,这是最通用的签名,并涵盖其他情况:

public getCache<T>(key: string, defaultValue?: T): T
{
    const result = localStorage.getItem(key);
    return result ? JSON.parse(result) as T : defaultValue;
}

请参见使用可选参数。我可以遵循指南,但如果我有不同输入参数的方法呢。我仍然需要修复这个错误。那么,如果泛型类型不相关,您就无法修复这个问题。您可以将方法放在一个类中,并将泛型类型放在该类中,以便所有方法都相同,或者干脆不使用重载。