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

Narrowing does not apply to array member / object element but should #48227

Closed
wbt opened this issue Mar 11, 2022 · 1 comment
Closed

Narrowing does not apply to array member / object element but should #48227

wbt opened this issue Mar 11, 2022 · 1 comment

Comments

@wbt
Copy link

wbt commented Mar 11, 2022

Bug Report

🔎 Search Terms

narrowing array member object element

🕗 Version & Regression Information

This is the behavior in every version I tried, and I reviewed the FAQ for entries about "Common "Bugs" That Aren't Bugs" and "Common Feature Requests"

⏯ Playground Link

Playground link with relevant code

💻 Code

const typeSafeJSFailsInTS = function(inputArray: ('' | Date)[], correspondingNames: string[]) {
	let result : {[index: string]: Date} = {};
	for(let index in inputArray) {
		if(inputArray[index] !== '') {
			result[correspondingNames[index]] = inputArray[index];
		}
	}
	return result;
}
const workaround = function(inputArray: ('' | Date)[], correspondingNames: string[]) {
	let result : {[index: string]: Date} = {};
	for(let index in inputArray) {
		const temporaryValue = inputArray[index];
		if(temporaryValue !== '') {
			result[correspondingNames[index]] = temporaryValue;
		}
	}
	return result;
}

🙁 Actual behavior

Error on line 5 (the most indented line):

Type '"" | Date' is not assignable to type 'Date'. Type 'string' is not assignable to type 'Date'. ts(2322)

This is wrong because it's inside a conditional block that narrows out the empty-string type from inputArray[index].

🙂 Expected behavior

The first example works just fine, with narrowing of the type working just as it does in the second.

Related issues

I don’t think this is a duplicate of #9998, despite how common duplicates are. This isn’t about other functions modifying the state or possibly expanding the type of a variable beyond a narrowing; there aren’t even multiple function calls involved. It’s not asynchronous, which was recently held to be a distinguishing feature of #9998.

I don’t think this is a duplicate of #18758 which is about narrowing the type of the parent based on the type/presence of deeper members, which is more complicated than what’s sought here, which is narrowing a specific member of an array rather than its parent.

@MartinJohns
Copy link
Contributor

Duplicate of #10530. Type narrowing does not occur for indexed access forms e[k] where k is not a literal.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants
@wbt @MartinJohns and others