-
Notifications
You must be signed in to change notification settings - Fork 12.6k
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
Infer bottom type for type argument when passing empty array #8878
Comments
Wouldn't There was also a lot of discussion of why |
function first<T>(xs: T[]): T | undefined {
return xs[0];
}
const z = first([]); |
var x = [];
x.push(5); needs to continue to work, so |
@Arnavion Agree, but I only wanted this for values of a parameter with a type argument. |
I thought the value of the generic parameter is derived from the type of the expression, so the fact that |
In general, that's true. Though with contextual typing, these types of the arguments will be inferred differently. For instance, the type of |
It could, but I can't see that being the intent in most cases. Almost every contextual type is as wide as can be inferred. You are suggesting this one of case (because you have a further widening challenge) to totally narrow down this one case to nothing. So far every use of |
The type I also found out that the following code doesn't work as expected. function concat<T>(xs: T[], ys: T[]): T[] {
return [...xs, ...ys];
}
const y = concat([], ["a"]); |
Starting with your last example, it is definitely a bug that function concat<T>(xs: T[], ys: T[]): T[] {
return [...xs, ...ys];
}
const y = concat([], ["a"]); It should be Now, regarding the original proposal to infer function a<T>(xs: T[]) {
return xs;
}
const x = a([]); // Could we infer never[]? We actually do infer However, even if we stopped widening in type inference, it isn't clear that we shouldn't widen when we're inferring a type for const a = [];
a.push(5); // Don't want an error here Contextual typing was also mentioned in the thread above, but that really doesn't have anything to do with widening. |
I did some edits to the comment above to fix some inaccuracies. It should be good now. |
I think the bottom type,
never
, could be used for this case: when passing an empty array to an argument of typeT[]
, whereT
is a type argument.@ahejlsberg What do you think?
TypeScript Version:
1.7.5 / 1.8.0-beta / nightly (1.9.0-dev.20160528-1.0)
Code
Expected behavior:
Type of
x
would benever[]
,y
would beNode[]
Actual behavior:
Type of
x
isany[]
,y
isany[]
.The text was updated successfully, but these errors were encountered: