Skip to content

Conversation

@Andarist
Copy link
Contributor

This patches a surprising difference in the inference behavior in respect to return types:

declare function test1<T>(value: T): T;

const result1 = test1("foo");
//    ^? const result1: "foo"

declare function test2<T>(value: T): T extends string ? T : never;

const result2 = test2("foo");
//    ^? const result2: string

The rule is that T has to appear in a top-level position in the return type for its literalness to be preserved. From the user's point of view ,it is in test2's top-level position in the return type. But since T in that truthy branch is seen as a substitution type for the compiler it fails to recognize it.

@typescript-bot typescript-bot added the For Uncommitted Bug PR for untriaged, rejected, closed or missing bug label Nov 30, 2024
@typescript-bot
Copy link
Collaborator

This PR doesn't have any linked issues. Please open an issue that references this PR. From there we can discuss and prioritise.

isTypeParameterAtTopLevel(getTrueTypeFromConditionalType(type as ConditionalType), tp, depth + 1) ||
isTypeParameterAtTopLevel(getFalseTypeFromConditionalType(type as ConditionalType), tp, depth + 1)
));
) || type.flags & TypeFlags.TemplateLiteral && some((type as TemplateLiteralType).types, t => isTypeParameterAtTopLevel(t, tp, depth))));
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TODO: handle TypeFlags.StringMapping too if this part of the PR turns out to be seen as a positive change too

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

For Uncommitted Bug PR for untriaged, rejected, closed or missing bug

Projects

Status: Not started

Development

Successfully merging this pull request may close these issues.

2 participants