-
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
Can't dereference array type in conditional type #22985
Comments
Not sure why that's not allowed. @ahejlsberg / @weswigham ? FWIW I would write it this way: export type RecursivePartial<T> = {
[P in keyof T]?: T[P] extends Array<infer E> ? {[index: number]: RecursivePartial<E>} :
T[P] extends object ? RecursivePartial<T[P]> : T[P];
}; |
The compiler does not recognize the constraints on anything that is not a naked type parameter in a conditional type in the true branch. so export type RecursivePartial<T> = {
[P in keyof T]?: Recursive<T[P]>;
};
type Recursive<T> = T extends Array<any> ? NI<T[number]>:
T extends object ? RecursivePartial<T> : T;
type NI<T> = { [x: number]: T }; |
We probably should rethink our design choices here. it is confusing that |
Actually I think @ahejlsberg just recently changed it (#22707) so we manufacture constraints for indexes and matching tuples, too. We should have it constrained here, afaik. |
It's a bug. The issue here is that we use |
@ceymard With the fix your example now compiles. That said, I'd suggest refactoring the conditional type inside the mapped type into a separate type alias: export type RecursivePartial<T> = {
[P in keyof T]?: RecursivePartialItem<T[P]>;
};
type RecursivePartialItem<T> =
T extends Array<any> ? { [index: number]: RecursivePartial<T[0]> } :
T extends object ? RecursivePartial<T> :
T; This type is distributive (because it operates on a naked type parameter) which ensures that the operation spreads itself over union types (e.g. |
@ceymard try infer T[P] like this
|
TypeScript Version: 2.8.1 and 2.9.0-dev.20180329
Search Terms:
I tried actually a lot of terms around mapped types, arrays, conditional types, array member dereferencing in mapped types etc..
Code
Expected behavior:
T[P][0]
is usable and doesn't produce an error, since T[P] extends any[] and should thus be indexable on [0] (it seems this is the way to dereference an array)Actual behavior:
I am getting
type 0 cannot be used to index type T[P]
.The odd part is that behaviour-wise it seems to be working ! I can't change the type of the nested
c
to anything other than string and I can't create random properties or what.Am I missing something ?
The text was updated successfully, but these errors were encountered: