Closed
Description
Bug Report
Cannot assign type which should be compatible when conditional generics are used (also posted on SO but was only suggested to open issue here)
🕗 Version & Regression Information
Throws error on all versions available in TypeScript playground.
Playground Link
💻 Code
// Returns keyes that have type extending Types
type KeysMatching<T, Types> = { [K in keyof T]: T[K] extends Types ? K : never }[keyof T];
type Mapping = {
STR: string;
NUM: number;
BOOL: boolean;
}
type Values = Mapping[keyof Mapping];
type Generic<T extends Values> = {
typeStr: KeysMatching<Mapping, T>
}
const foo: Generic<boolean> = { typeStr: 'BOOL' };
const bar: Generic<Values> = foo;
// Type 'Generic<boolean>' is not assignable to type 'Generic<Values>'.
// Type 'Values' is not assignable to type 'boolean'.
// Type 'string' is not assignable to type 'boolean'.(2322)
// This works fine
type Conditional<T, V> = T extends V ? T : unknown;
const foo2: Conditional<string, Values> = 'string';
const bar2: Conditional<Values, Values> = foo2;
🙁 Actual behavior
TS throws error that foo is not assignable to bar
🙂 Expected behavior
TS does not throw error as the types should be compatible
Metadata
Metadata
Assignees
Type
Projects
Milestone
Relationships
Development
No branches or pull requests
Activity
whzx5byb commentedon Sep 7, 2022
A shorter repro:
Expect both to be true but
R1
is false.Related: #48070
fatcerberus commentedon Sep 7, 2022
Probably something to do with variance measurement - it seems like
V<T>
is incorrectly being measured as contravariant/invariant inT
, likely becauseT
occurs on the RHS of anextends
check.R2
is correctly determined to be true becauseV0 extends VNumber
bypasses variance measurement and does a full structural check.andrewbranch commentedon Sep 9, 2022
Yeah, duplicate of #48070
typescript-bot commentedon Sep 12, 2022
This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes.