Skip to content
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

Type guards don't infer generic types #39727

Closed
purplesyringa opened this issue Jul 24, 2020 · 5 comments
Closed

Type guards don't infer generic types #39727

purplesyringa opened this issue Jul 24, 2020 · 5 comments
Labels
Working as Intended The behavior described is the intended behavior; this is not a bug

Comments

@purplesyringa
Copy link

TypeScript Version: 4.0.0-dev.20200724

Search Terms: generics, type guard, typeof

Code

function func<T>(object: T): T {
	if(typeof object === "number") {
		return 1;
	} else {
		return object;
	}
}

Expected behavior:

The code compiles. It is obvious that if typeof object === "number", then T must be number, and 1 is a number.

Actual behavior:

The code yields:

test.ts:3:3 - error TS2322: Type '1' is not assignable to type 'T'.
  'T' could be instantiated with an arbitrary type which could be unrelated to '1'.

3  	return 1;
   	~~~~~~~~~


Found 1 error.

Playground Link: There we go

Related Issues: none

@RyanCavanaugh RyanCavanaugh added the Working as Intended The behavior described is the intended behavior; this is not a bug label Jul 24, 2020
@RyanCavanaugh
Copy link
Member

RyanCavanaugh commented Jul 24, 2020

This is a correct error for the reason described in the error message.

// Causes the value '1' to inhabit an expression of type '2'
const a = func<2>(2);

@purplesyringa
Copy link
Author

purplesyringa commented Jul 24, 2020

@RyanCavanaugh Perhaps that was a wrong example. My actual code is similar to:

function func<T>(object: T): T extends Number ? number : T {
	if(object instanceof Number) {
		return object.valueOf();
	} else {
		return object;
	}
}

I don't see how func<2>(2) or similar would apply here.

I'll reopen the issue and change the code in the first comment if this turns out to be a bug.

@RyanCavanaugh
Copy link
Member

RyanCavanaugh commented Jul 24, 2020

#33014 / #33912

@purplesyringa
Copy link
Author

Sorry for duplicates. I'll try to search better next time.

@RyanCavanaugh
Copy link
Member

Those ones are hard for me to find 😅

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Working as Intended The behavior described is the intended behavior; this is not a bug
Projects
None yet
Development

No branches or pull requests

2 participants