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

Proposal: Add not #32

Open
younho9 opened this issue Jan 28, 2022 · 5 comments
Open

Proposal: Add not #32

younho9 opened this issue Jan 28, 2022 · 5 comments

Comments

@younho9
Copy link
Contributor

younho9 commented Jan 28, 2022

const isNullable = (value: unknown): value is null | undefined =>
	value === null || value === undefined;

const isNonNullable = not(isNullable);

declare const someValue: string | null | undefined;

if (isNonNullable(someValue)) {
	someValue;
	//=> string
}

It could be useful to reuse existing predicate.

use-case: TypeScript Playground

@jonahsnider
Copy link
Contributor

Is inverting the return type of a type guard possible with TypeScript's type system?

@younho9
Copy link
Contributor Author

younho9 commented Jan 29, 2022

It depends on Exclude type. Type guard using Exclude can exclude some types from a given type.

microsoft/TypeScript#4183 (comment)

type Predicate<Type> = (value: unknown) => value is Type;

function not<Type>(predicate: Predicate<Type>) {
    return <Value>(value: Value): value is Exclude<Value, Type> => !predicate(value);
};

const isNullable = (value: unknown): value is null | undefined =>
	value === null || value === undefined;

const isNonNulluable = not(isNullable);
//=> <Value>(value: Value) => value is Exclude<Value, null | undefined>

use-cases:

  • Nullable <-> NonNullable
  • Falsy <-> Truthy

@tychenjiajun
Copy link
Contributor

tychenjiajun commented Feb 11, 2022

@younho9 I don't think this will work with isEmpty or isInfinite. It's not only depends on Exclude but also depends on negated type. microsoft/TypeScript#29317

@younho9
Copy link
Contributor Author

younho9 commented Feb 13, 2022

@younho9 I don't think this will work with isEmtpy or isInfinite. It's not only depends on Exclude but also depends on negated type. microsoft/TypeScript#29317

Yes, when this PR merge, the negated type guards will be more useful.

Negative type guards (with Exclude) do not narrow types in some situations.

But I still think some types guards with Exclude are useful.

@fregante
Copy link
Contributor

Related type-only request:

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

4 participants