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

Inferred Type Predicates doesn't narrow type if using other conditional expressions #59509

Closed
zyoshoka opened this issue Aug 2, 2024 · 3 comments

Comments

@zyoshoka
Copy link

zyoshoka commented Aug 2, 2024

πŸ”Ž Search Terms

"Inferred Type Predicates"

πŸ•— Version & Regression Information

5.6.0-dev.20240801

⏯ Playground Link

https://www.typescriptlang.org/play/?ts=5.6.0-dev.20240801#code/C4TwDgpgBA8lC8UDeUDWEQC4oGdgCcBLAOwHMoBfAbgCgBjAe2LygYCMArHbACjgB8oxAK4AbUQEoA2gF0EUKSnRYoAcgCGqygBpkaDNlVstFXSPEzajZsCgAzQqOAR8EACYBGeey4A6B04uPDgIAHy4UACEiOaSVFAA9AmwsvRMLAHOrm4ATN6cOP6OWcFhEdFCYqJQAGQ1uL7KCIgaqhLxSVB8UIKx0jJpNvbFLu4AzPl+mUEh8OEhFX1Fgfilcw1N8C2a7YnJMKlAA

πŸ’» Code

type O = { key: string };
const objs: (O | null)[] = [{ key: 'a' }, { key: 'b' }, null];
const filtered1 = objs.filter(s => s != null); // O[]
const filtered2 = objs.filter(s => s != null && s.key == 'a'); // (O | null)[]
const filtered3 = objs.filter(s => s != null).filter(s => s.key == 'a'); // O[]

πŸ™ Actual behavior

The type inferred for filtered2 is (O | null)[] instead of O[].

πŸ™‚ Expected behavior

I would expect filtered2 to have the inferred type O[], similar to filtered1 and filtered3.

Additional information about the issue

No response

@MichalMarsalek
Copy link

MichalMarsalek commented Aug 2, 2024

This is working as intended. There are no one-sided typeguards.
The second case cannot be inferred as s is O, because if s.key != 'a', s can still be O.

@jcalz
Copy link
Contributor

jcalz commented Aug 2, 2024

See #57465, where it mentions #15048

@zyoshoka
Copy link
Author

zyoshoka commented Aug 2, 2024

Got it, thank you. I'm closing this issue.

@zyoshoka zyoshoka closed this as not planned Won't fix, can't repro, duplicate, stale Aug 2, 2024
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