Makla
Makla

Reputation: 10459

ReSharper: Typescript error Return types are not relatable

I get return types are not relatable

Overload signature is not compatible with function definition: Return types are not relatable

error with ReSharper plugin in this

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;
}

TypeScript code.

I can see why. Generic parameter T in first overload has nothing in common with T in second overload. I could just write

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;
}

Is there solution for this problem?
My ReSharper version is 2017.3 (15.5.27130.2024)

enter image description here

Upvotes: 0

Views: 74

Answers (1)

Wickoo
Wickoo

Reputation: 7387

Since TypeScript has optional parameters, an overload doesn't make sense in this case. Simply use the last signature, which is the most generic one and cover other cases:

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

See https://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html (Use Optional Parameters)

Upvotes: 1

Related Questions