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

Incorrect inferring of return type #31254

Closed
cevek opened this issue May 4, 2019 · 6 comments
Closed

Incorrect inferring of return type #31254

cevek opened this issue May 4, 2019 · 6 comments
Labels
Duplicate An existing issue was already created

Comments

@cevek
Copy link

cevek commented May 4, 2019

Version: 3.4.5

declare function abc<T>(q: T | [{id: 'Id'}]): T 
var x = abc([{id: 'Id'}]).map(v => v.id /* 'Id' */) // string[] 

var y = abc([{id: 'Id'}]).map(v => v.id as 'Id') // 'Id'[]
@NN---
Copy link

NN--- commented May 4, 2019

Related: #30680

It is due to widening.
If you want to narrow type you have to specify explicitly as you did or use some tricks.

@jcalz
Copy link
Contributor

jcalz commented May 5, 2019

effort level matching answer: don’t see a bug here, try SO

@weswigham weswigham added Bug A bug in TypeScript Domain: Quick Info e.g. hover text, tool-tips, and tooltips. labels May 8, 2019
@weswigham
Copy link
Member

weswigham commented May 8, 2019

I'd refer to #241 for explaining away a return type being wider than expected

@weswigham weswigham added Duplicate An existing issue was already created and removed Bug A bug in TypeScript Domain: Quick Info e.g. hover text, tool-tips, and tooltips. labels May 8, 2019
@cevek
Copy link
Author

cevek commented May 9, 2019

Something strange happens here

declare function abc<T>(q: T | {id: 'Id'}[]): T 
var u = abc([{id: 'Id'}]) // -> {id: 'Id'}[]
var k:{id: 'Id'}[] = u; // no problem
var l:typeof u = k; // no problem
var e:{id: 'Id'}[] = {} as {id: string}[]; // error (correct)
var p = k.map(v => v.id); // -> 'Id'[]
var t = l.map(v => v.id); // -> string[] (incorrect)

@weswigham
Copy link
Member

weswigham commented May 9, 2019

k's literal type isn't "fresh" since it came from a type position instead of an expression, so isn't widened. (While since l is typeof u it's still fresh)

@typescript-bot
Copy link
Collaborator

This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

5 participants