Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

no-useless-assertion: false positive when disabling no-misused-generics #625

Closed
AlCalzone opened this issue Jun 3, 2019 · 2 comments
Closed

Comments

@AlCalzone
Copy link

Consider the following code:

/* wotan-disable no-misused-generics */
function foo<T = unknown>(): T {
	return ({} as any) as T;
}

const bar = foo() as string;
console.log(bar.length);

wotan complains about the as string being a useless assertion. However when I remove it, the type of bar changes to unknown, making the last line illegal.

@ajafff
Copy link
Member

ajafff commented Jun 3, 2019

I remember seeing this in the TSLint repo. This was discussed in palantir/tslint#3540 and microsoft/TypeScript#20681

TL;DR: this not only occurs when disabling no-misused-generics, but every time a call(like) expression has no inference candidate for a type parameter used in the return type. Instead of using the declared fallback the type is inferred from the contextual type. In this case the contextual type comes from the type assertion. If you remove the assertion, there's no contextual type and therefore the type parameter default applies.

You can work around this design limitation by providing the contextual type by any other means:

const bar: string = foo(); // 'T' is inferred as 'string'

I don't think this can be fixed in this project. If you care enough about this issue, please consider opening a new issue with TypeScript.

@AlCalzone
Copy link
Author

If you care enough about this issue

I don't, since I can just pass the intended type in the angled brackets. I just thought the behavior is weird.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants