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 guard not working in returned function #12616

Closed
andraaspar opened this issue Dec 2, 2016 · 2 comments
Closed

Type guard not working in returned function #12616

andraaspar opened this issue Dec 2, 2016 · 2 comments
Labels
Working as Intended The behavior described is the intended behavior; this is not a bug

Comments

@andraaspar
Copy link
Contributor

TypeScript Version: 2.2.0-dev.20161202

Code

function getGetter() {
	let data = {}
	data['bar'] = 1
	
	if (hasBar(data)) {
		return () => data.bar // Property 'bar' does not exist on type '{}'.
	}
}

function hasBar(thing): thing is {bar: number} {
	return typeof thing.bar == 'number'
}

Expected behavior:
Compile successfully.

Actual behavior:

index.ts(6,21): error TS2339: Property 'bar' does not exist on type '{}'.
@ahejlsberg
Copy link
Member

Your example works if you use const to declare data. Type guards for let variables are not in effect in nested functions because the variable might be reassigned. See #8849.

@ahejlsberg ahejlsberg added the Working as Intended The behavior described is the intended behavior; this is not a bug label Dec 3, 2016
@andraaspar
Copy link
Contributor Author

I see. You are right.

@microsoft microsoft locked and limited conversation to collaborators Jun 19, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
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