-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Filtering keys by property type doesn't narrow the actual property types #28111
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
Comments
I don't necessarily know what we could do to keep track of that information. By the time the keys from |
I have a similar problem. Why is type StringLiteral = 'a'
type Value = { [key in StringLiteral]: string }
type StringKeys<V extends Value> = { [K in keyof V]: V[K] extends string ? K : never }[keyof V]
function test<V extends Value>(str: StringKeys<V>) {
const assignable: string = str as string
// TS2322: Type 'number' is not assignable to type 'string'.
const notAssignable1: string | number | undefined = str
const notAssignable2: StringLiteral = str
} |
@jacobmadsen same issue as Daniel cited above - by the time the final indexing |
Currently there is no way to infer that all keys of type |
Maybe the error message should be:
|
With TypeScript v3.5.1, I want to write: type PossibleKeys<T, V, K extends keyof T = keyof T> = T[K] extends V ? K : never; But finally I can only write type PossibleKeys<T, V, K extends keyof T = keyof T> =
K extends keyof T
? T[K] extends V ? K : never
: never; |
The original example works when written as follows: type WantedTypes = string | number
type WantedKeys<T> = { [K in keyof T]: T[K] extends WantedTypes ? K : never }[keyof T]
function foo<T extends Record<K, WantedTypes>, K extends WantedKeys<T>>(obj: T, key: K) {
return obj[key];
}
class DerivedProperty<T extends WantedTypes> { }
type Derived<T extends Record<K, WantedTypes>, K extends WantedKeys<T> = WantedKeys<T>> = {
[K in WantedKeys<T>]: DerivedProperty<T[K]>
} The key here is to ensure |
@gdh1995 That's the intended behavior. The first form is not a distributive conditional type, but the second form is (see #21316 for definition). You could also write it as any one of the following: K extends K ? T[K] extends V ? K : never : never;
K extends any ? T[K] extends V ? K : never : never;
K extends unknown ? T[K] extends V ? K : never : never; |
TypeScript Version: 3.2.0-dev.20181023
Search Terms:
keyof, filter, type is not assignable to type
Code
Expected behavior:
Compiles without errors.
Actual behavior:
I couldn't find any similar issues here.
The text was updated successfully, but these errors were encountered: