Skip to content

Variance Annotations do not impact "infer" correctlyΒ #55920

Closed as not planned
Closed as not planned
@CraigMacomber

Description

@CraigMacomber

πŸ”Ž Search Terms

Variance Annotations, infer, extends, type

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried (4.7 +), and I reviewed the FAQ for entries about "bugs-that-arent-bugs"

⏯ Playground Link

https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgEJTiAJgHlMgewFcxkAVAPmQG8BfAKDAE8AHFAJQgGciAbUgLzIAFNSIgoEXnEhYAYsClYAXMhBEAtgCNotZADI0GbDi5gooAOYUAlMggAPSNi5HMuUDGjkqAfnLIqiAQAG7QANxAA

πŸ’» Code

interface Brand<in out T> {}
type Result = ({unrelatedField: number} & Brand<string>) extends Brand<infer T> ? T : never;

πŸ™ Actual behavior

Result is unknown

This is incorrect since the inferred type parameter is "string" not "unknown". Additionally, "unknown" is not referred to anywhere in this code, so it's very strange for it to get inferred.

πŸ™‚ Expected behavior

Result is string since the type extends Brand<string>.

This is how the example behaves if the "unrelatedField" is removed. Since that field is unrelated to the extends clause, it should have no impact on the inferred type. This is further evidence that "string" is the right result, but this case is messing that up somehow.

Additional information about the issue

Another workaround for this is to explicitly reference the type parameter in dummy fields. This is the pattern taken in my TypeCheck library to enable it to control variance before TypeScript 4.7. I found this issue when updating usages of that library to use the built-in variance annotation feature, and it broke some usages of infer.

Metadata

Metadata

Assignees

Labels

Has ReproThis issue has compiler-backed repros: https://aka.ms/ts-reprosNot a DefectThis behavior is one of several equally-correct options

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions