-
Notifications
You must be signed in to change notification settings - Fork 12.5k
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
Inferring type from a generic constraint #54673
Comments
I'm pretty sure this is a duplicate, but I can't find the other issue(s) at the moment. This is interesting. I was initially thinking you could already do this by adding an additional type parameter, but it turns out that doesn't work either: function foo<U, T extends Array<U>>(array: T): Array<NonNullable<U>> {
// ...
};
const food: string[] = [ "foo", "bar" ];
foo(food); // infers U = unknown :( Which makes sense now that I think about it because constraints aren't considered inference sites (which incidentally might make this proposal DOA). |
After further searching, I think this is a duplicate of, or at least strongly related to, #52791. |
Ahh, the guy used the other jargon - conditional vs constraint π (it is called a constraint, right?) |
Constraint: Conditional: |
This issue has been marked as 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes. |
Suggestion
π Search Terms
infer, generic, constraint
β Viability Checklist
My suggestion meets these guidelines:
β Suggestion
It doesn't seem possible yet, to use an inferred type from a generics constraint. An example will show what I mean:
π Motivating Example
I feel like I should be able to write something like this:
So this would infer the U out of the Array type constraint, giving me effectively the type of items in that array. I could then use that type to construct another type based on it.
π» Use Cases
This particular example can be rewritten to not require this feature request:
But this has two disadvantages:
Advantages of having this feature would not be limited to arrays. It would mean that given a certain constraint, is becomes possible to use the generic types that are enclosed in that type. So, another potential use-case would be:
Here, rewriting it to match the current way typescript works:
Apart from more repetition and (as said before) losing the generic type parameter of
record
, it's all about how to call this function. I can no longer just plonk therecord
type into this function, but am now required to put in whatever is contained within it. I may not have that information. This is of course only in case I need to explicitly pass the generics parameters.The text was updated successfully, but these errors were encountered: