Skip to content

Type Guards do not reflect on related types #25040

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

Closed
lingz opened this issue Jun 18, 2018 · 6 comments
Closed

Type Guards do not reflect on related types #25040

lingz opened this issue Jun 18, 2018 · 6 comments
Labels
Question An issue which isn't directly actionable in code

Comments

@lingz
Copy link

lingz commented Jun 18, 2018

TypeScript Version: 2.8

Code

type Identity<T> = T;

function test(
  x: 'a' | 'b',
  y: Identity<typeof x>,
) {
  if (x === 'a') {
    const z = y;
  }
}

Expected behavior:
x has type a
z has type a

Actual behavior:
x has type a
z has type a | b

@MartinJohns
Copy link
Contributor

MartinJohns commented Jun 18, 2018

typeof x is 'a' | 'b', so y can either be 'a' or 'b', independently of the value of x. Calling test('a', 'b') is perfectly valid.

@j-oliveras
Copy link
Contributor

You can use function overloads (if you want that the two parameters has the same type):

type Identity<T> = T;

function test(x: 'a', y: Identity<typeof x>);
function test(x: 'b', y: Identity<typeof x>);
function test(
  x: 'a' | 'b',
  y: Identity<typeof x>,
) {
  if (x === 'a') {
    const z = y;
  }
}

See at playground.

@MartinJohns
Copy link
Contributor

@j-oliveras But that won't fix his issue that z is still 'a' | 'b', and not the actual type of y. Tho this sounds like a very constructed case. Perhaps he can shed some light on his actual use-case.

@lingz
Copy link
Author

lingz commented Jun 18, 2018

I'm trying to understand if there is a way to constrain a function arguments with some relation, i.e. having the same type. For example, what if I want a function that takes two arguments of the same type:

f<T>(a: T, b: T)

Within the implementation, narrowing does not work with generics at all #25039. So we need to write it without generics, but it seems that there is no way to express this relation without using generics?

@jcready
Copy link

jcready commented Jun 18, 2018

This would require dependent types which is not something that TypeScript offers.

@RyanCavanaugh RyanCavanaugh added the Question An issue which isn't directly actionable in code label Jun 18, 2018
@typescript-bot
Copy link
Collaborator

Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Question An issue which isn't directly actionable in code
Projects
None yet
Development

No branches or pull requests

6 participants