-
Notifications
You must be signed in to change notification settings - Fork 12.5k
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 not automatically changing after .filter #47194
Comments
Duplicate of #20218. You're not passing a type guard function to |
In these situations I feel like it would be helpful for TypeScript to infer these functions as typeguards automatically. In particular if we have one of the following callbacks to infer as a typeguard: v => v != undefined; // or null
v => typeof v === "string"; // and others
v => v instanceof SomeClass;
v => v === "someLiteral"; // and other types
// ideally disriminants as well but this might be harder to statically analyze
v => v.kind === "someKind" |
@Jamesernator See #38390. |
Im doubt that it would work. I do miss your specific solution. This type guard does not work correct type A = string | undefined
const array: A[] = ['hello', undefined, 'salve'];
const a1 = array.filter((e): e is string => e == undefined); because a1 is type string[] but got no string value, got only undefined. |
Potential SolutionThis solution works // Create this helper function
function isNotNullOrUndefined<T extends Object>(input: null | undefined | T): input is T {
return input != null;
}
// This actually determines that result is of type (string)[]
let correctStringArray = mixedArray.filter(isNotNullOrUndefined); Source / found in 16069 |
Type guards are not checked for correctness. You can say the very same about the helper function from your last comment. |
I should probably split this out into a separate The method it sounds like you want is notNil. |
Bug Report
Type not automatically changing after .filter
🔎 Search Terms
typescript error filter undefinied
Found
issue 20707
issue 20812
🕗 Version & Regression Information
Typescript 4.5.3 and below
ESNext and below
Please keep and fill in the line that best applies:
⏯ Playground Link
Playground Link
💻 Code
🙁 Actual behavior
🙂 Expected behavior
The text was updated successfully, but these errors were encountered: