Closed
Description
(sorry for the bad title, I really didn't know how to describe this at all, and I've tried reaching out to some other developers who hade no idea either 😬 For the same reason I've also had a hard time searching for similar issues, and didn't really find anything)
TypeScript Version: 3.8.0-dev.20200208 (and 3.7.5)
Search Terms: "is not assignable to"
Code
interface Base { _id: string }
interface Car extends Base { make: string }
interface Pet extends Base { name: string }
interface Collection<T> {
find(filter: Partial<T>): Promise<T[]>
}
declare const collections: {
car: Collection<Car>
pet: Collection<Pet>
}
type ExtractCollection<T extends keyof typeof collections> = (typeof collections)[T] extends Collection<infer R> ? R : never
// $ExpectType Promise<Pet[]>
let a = collections.pet.find({ name: 'test' })
// $ExpectType Car
let b: ExtractCollection<'car'>
// $ExpectType Car | Pet
let c: ExtractCollection<'car' | 'pet'>
// $ExpectType Promise<Car[]>
let d = findById('car', 'test')
function findById<T extends keyof typeof collections>(name: T, id: string): Promise<Array<ExtractCollection<T>>> {
return collections[name].find({ _id: id }) // <------ Type 'Pet' is not assignable to type 'ExtractCollection<T>'
}
Expected behavior:
I expected no error since ExtractCollection<'pet'>
resolves to Pet
.
Actual behavior:
Type
Pet
is not assignable to typeExtractCollection<T>
Related Issues: no 😢