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

Suggestion: Add support for non-null assertion operator on function arguments #16822

Closed
jinder opened this issue Jun 29, 2017 · 2 comments
Closed

Comments

@jinder
Copy link

jinder commented Jun 29, 2017

When operating on an array, it's quite common to filter it to ensure there are no null or undefined values. Unfortunately, this doesn't narrow the type further. This means that if you subsequently use the value in strict mode, you have to either cast it to a non-nullable type, or use the non-null assertion operator.

I would like to suggest the ability to use the ! operator on the function arguments themselves, rather than on every scenario when you use the value.

const array1: Array<{ test: string } | undefined> = [];

// Won't compile as x is possibly undefined
array1.filter(x => !!x).map(x => x.test);

// Current fix:
array1.filter(x => !!x).map(x => x!.test);

// Or:
array1.filter(x => !!x).map((x: { test: string }) => x.test);

// SUGGESTION: This would be better because you can use x multiple times without adding ! every time:
array1.filter(x => !!x).map(x! => x.test);
@ikatyang
Copy link
Contributor

I think you need some type-predicates to narrow the type:

declare const array1: Array<{ test: string } | undefined>;
declare function is_non_null<T>(value: T | undefined): value is T;

array1.filter(is_non_null).map(x => x.test);
// no error                    ^ x === { test: string }

(lib.es6.d.ts)

interface Array<T> {
  filter<S extends T>(callbackfn: (value: T, index: number, array: T[]) => value is S, thisArg?: any): S[];
  filter(callbackfn: (value: T, index: number, array: ReadonlyArray<T>) => any, thisArg?: any): T[];
}

@RyanCavanaugh
Copy link
Member

Seems like #16069 is what you really want.

I don't think we'd be keen to add new punctuation to function parameters unless it was extremely compelling. There are a lot of other ways to fix this specific scenario

@jinder jinder closed this as completed Jul 7, 2017
@microsoft microsoft locked and limited conversation to collaborators Jun 14, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants