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: one-sided or fine-grained type guards #15048

Open
mcmath opened this issue Apr 6, 2017 · 39 comments · May be fixed by #52255
Open

Suggestion: one-sided or fine-grained type guards #15048

mcmath opened this issue Apr 6, 2017 · 39 comments · May be fixed by #52255
Labels
Awaiting More Feedback This means we'd like to hear from more people who would be helped by this feature Suggestion An idea for TypeScript

Comments

@mcmath
Copy link

mcmath commented Apr 6, 2017

The Problem

User-defined type guards assume that all values that pass a test are assignable to a given type, and that no values that fail the test are assignable to that type. This works well for functions that strictly check the type of a value.

function isNumber(value: any): value is number { /* ... */ }

let x: number | string = getNumberOrString();

if (isNumber(x)) {
  // x: number
} else {
  // x: string
}

But some functions, like Number.isInteger() in ES2015+, are more restrictive in that only some values of a given type pass the test. So the following does't work.

function isInteger(value: any): value is number { /* ... */ }

let x: number | string = getNumberOrString();

if (isInteger(x)) {
  // x: number (Good: we know x is a number)
} else {
  // x: string (Bad: x might still be a number)
}

The current solution – the one followed by the built-in declaration libraries – is to forgo the type guard altogether and restrict the type accepted as an argument, even though the function will accept any value (it will just return false if the input is not a number).

interface NumberConstructor {
  isInteger(n: number): boolean;
}

A Solution: an "as" type guard

There is a need for a type guard that constrains the type when the test passes but not when the test fails. Call it a weak type guard, or a one-sided type guard since it only narrows one side of the conditional. I would suggest overloading the as keyword and using it like is.

function isInteger(value: any): value as number { /* ... */ }

let x: number | string = getNumberOrString();

if (isInteger(x)) {
  // x: number
} else {
  // x: number | string
}

This is only a small issue with some not-too-cumbersome workarounds, but given that a number of functions in ES2015+ are of this kind, I think a solution along these lines is warranted.

A more powerful solution: an "else" type guard

In light of what @aluanhaddad has suggested, I feel the above solution is a bit limited in that it only deals with the true side of the conditional. In rare cases a programmer might want to narrow only the false side:

let x: number | string = getNumberOrString();

if (isNotInteger(x)) {
  // x: number | string
} else {
  // x: number
}

To account for this scenario, a fine-grained type guard could be introduced: a type guard that deals with both sides independently. I would suggest introducing an else guard.

The following would be equivalent:

function isCool(value: any): boolean { /* ... */ }
function isCool(value: any): true else false { /* ... */ }

And the following would narrow either side of the conditional independently:

let x: number | string = getNumberOrString();

// Narrows only the true side of the conditional
function isInteger(value: any): value is number else false { /* ... */ }

if (isInteger(x)) {
  // x: number
} else {
  // x: number | string
}

// Narrows only the false side of the conditional
function isNotInteger(value: any): true else value is number { /* ... */ }

if (isNotInteger(x)) {
  // x: number | string
} else {
  // x: number
}

For clarity, parentheses could optionally be used around one or both sides:

function isInteger(value: any): (value is number) else (false) { /* ... */ }

At this point I'm not too certain about the syntax. But since it would allow a number of built-in functions in ES2015+ to be more accurately described, I would like to see something along these lines.

@RyanCavanaugh RyanCavanaugh added In Discussion Not yet reached consensus Suggestion An idea for TypeScript labels Apr 6, 2017
@krryan
Copy link

krryan commented Apr 7, 2017

Just ran into a case where I want exactly this. Strongly agree with this idea. Not sure about as vs. is being the syntactical distinguishing feature, but definitely want a one-sided type-guard in some fashion.

@aluanhaddad
Copy link
Contributor

function isInteger(value: any): value as number { /* ... */ }

Just bikeshedding here but I would prefer a syntax that was either more intuitive or more explicit. The as might be familiar to C# programmers as a conditional reference conversion but the analogy is a stretch.

What about

function isInteger(value: any): (value is number) | false { /* ... */ } 

@mcmath mcmath changed the title Suggestion: one-sided type guards Suggestion: one-sided or fine-grained type guards Apr 9, 2017
@mcmath
Copy link
Author

mcmath commented Apr 9, 2017

@aluanhaddad Actually, I think something along those lines would be more powerful – not just more intuitive – since it would allow for independent control over both the true and false sides of the conditional.

I would suggest using else instead of | to separate each side, as the following could be confused, especially in more complicated cases with a lot of parentheses:

function isInteger(value: any): value is number | false;
function isInteger(value: any): (value is number) | false;

I've updated my suggestion in light of your comments.

@aluanhaddad
Copy link
Contributor

@mcmath I like the idea of using else to reduce parentheses, but I was actually not proposing branching.

I was proposing

function isInteger(value: any): value is number else false

simply as the syntactic form for writing a one-sided type guard.

That said, I like where you went with it. It does indeed open up a lot of power.

@krryan
Copy link

krryan commented Apr 9, 2017

I almost suggested | myself, but I like else a lot more. But ultimately I held off on the |/else suggestion because it's a kind of weird case where value is number implies value is number else not number which relies on type negation/subtraction (another feature I very, very much want). Basically, it's kind of confusing that the two-sided type-guard is the default.

@RyanCavanaugh RyanCavanaugh added Awaiting More Feedback This means we'd like to hear from more people who would be helped by this feature and removed In Discussion Not yet reached consensus labels Apr 24, 2017
@RyanCavanaugh
Copy link
Member

It'd be good to collect some more use cases here.

The main objection from the design meeting was that once there are two different kinds of type guards, there's an additional cognitive load for people to choose one or the other correctly.

@mcmath
Copy link
Author

mcmath commented Apr 25, 2017

Three kinds of use case

@RyanCavanaugh: I agree the extra complexity would be unwarranted if there were too few practical use cases. There are a lot of cases where predicate functions could be more
accurately described with this proposal; but such accuracy may not be necessary
in many cases.

That said, there are three general kinds of case where this kind of type guard
could be put to use:

  • describing new predicate functions introduced in ES2015,
  • describing changes to the behavior of ES5 functions introduced in ES2015,
  • describing custom functions whose behavior matches these built-in functions

I'm going to assume the else syntax in the examples below, but I'm not
suggesting that should be the final syntax.

New ES2015+ predicate functions

The predicate functions added in ES2015 as static methods of the Number
constructor accept any value, and return false when passed non-number values.
TypeScript currently describes them as accepting only numbers:

function isNaN(value: number): boolean;
function isFinite(value: number): boolean;
function isInteger(value: number): boolean;
function isSafeInteger(value: number): boolean;

With this proposal, these could be described more accurately as follows:

function isNaN(value: any): value extends number else false;
function isFinite(value: any): value extends number else false;
function isInteger(value: any): value extends number else false;
function isSafeInteger(value: any): value extends number else false;

Changes to existing predicate functions in ES2015+

Along similar lines, ES2015 modifies the behavior of several static methods of
the Object constructor initially introduces in ES5. TypeScript
currently describes them as follows:

function isExtensible(value: any): boolean;
function isFrozen(value: any): boolean;
function isSealed(value: any): boolean;

These methods throw a TypeError when passed a non-object in ES5. Even in ES5,
they should be described like so:

function isExtensible(value: object): boolean;

But in ES2015+, they return false when passed a primitive
value. So with this proposal, they would be described as follows, but only
when targeting ES2015 and above:

function isExtensible(value: any): value as object else false;

This kind of case is a bit more challenging than the first, as the TypeScript's
ES2015 declarations currently reference the ES5 declarations.

User-defined predicate functions

In keeping with the ES2015+ way of defining predicate functions, a TypeScript
user might want to define any number of similar functions.

/**
 * Tests whether a value is a non-negative integer.
 * Non-numbers return false.
 */
function isWholeNumber(value: any): value is number else false;
/**
 * Tests whether a value is a string of length 1.
 * Non-strings return false.
 */
function isCharacter(value: any): value is string else false;
/**
 * Tests whether a value is an empty array.
 * Non-arrays return false.
 */
function isEmpty(value: any): value is any[] else false;

@m93a
Copy link

m93a commented Oct 20, 2018

I'm writing code where I frequently need to check whether a variable is a function or an object, but not null. I need that to decide whether I should use Map or WeakMap.
I wanted to move the type check to a type guard function, so that I don't have to write (typeof x === "object" || typeof x === "function") && x !== null over and over. However as the current type guards are only an implication of a type, not equivalence, I can't do it without making the types less strict.

I think that the x is T else false seems good to me, as the addition makes it clear it's stricter. People who don't need the fine-grained type guard don't even need to know it exists. Adding cognitive to programmers doesn't seem like a good reason not to implement it – either you use the "normal" type guard, or something doesn't work, you google it and change that to the "strict" type guard. Not much to think about.

It really bugs me when I design a module with really good, strict types and then I have to relax them because “not enough people need types this strict“, so the feature won't be implemented 🙁

@UselessPickles
Copy link

UselessPickles commented Jan 9, 2019

Another related use case: an "isEmpty" function, like lodash's _.isEmpty would be more useful if a false result could indicate to the compiler that the param is not null | undefined.

Here's a current annoying behavior:

declare const someArray: number[] | undefined;

if (!_.isEmpty(someArray)) {
    // compiler error: someArray may be undefined.
    // requires a non-null assertion event though I know it's a non-empty array
    console.log(someArray[0]);
}

A solution to this would require being able to specify the type guard in terms of a false result, rather than a true result. That would basically be the exact inverse of current custom type guards, but would not solve the OP's issue. A solution that takes care of both situations would be best.

NOTE: It is currently easy to implement the inverse of isEmpty as a type guard as follows:

export function isNonEmpty<T>(value: T | undefined | null): value is T {
    return !_.isEmpty(value);
}

@RenaudF
Copy link

RenaudF commented Jun 9, 2019

This SO seems like a valid use case

@jcalz
Copy link
Contributor

jcalz commented Sep 23, 2019

I think this SO question also wants this feature.

@krryan
Copy link

krryan commented Sep 24, 2019

For what it’s worth, you can always work around this by making your type-guard even more fine-grained: if you use value is TheClass & { someOtherValueYouChecked: 'foobar' }, then false results will just mean it’s either not a member of TheClass or else it is but someOtherValueYouChecked wasn’t foobar—which is exactly correct.

The shortcoming is when the other values you check aren’t things you can indicate in the type domain. Even there, though, you can use “type brands,” “type tags,” or whatever you want to call them to get a nominal type to indicate this—the brand means nothing in the positive case, but in the negative case it indicates, again, that the argument is not necessarily not the class in question, but rather not the intersection of that and the brand.

One-sided type-guards might still be convenient—it’s not always trivial to indicate the real type, and producing a brand type just for this is annoying. But they don’t actually make things more type-safe. I have eliminated all of the cases in our code that were looking for one-sided type-guards using these approaches.

@jcalz
Copy link
Contributor

jcalz commented Sep 24, 2019

@krryan That's awesome!!

@krisdages
Copy link

krisdages commented Jan 19, 2020

I ran into this issue with Array.isArray... I'm sure there's another issue somewhere related to this specifically, but the current arr is any[] return type would benefit from a definition with one of these syntaxes.

A syntax like

declare interface ArrayConstructor {
    isArray(arr: any): arr is readonly unknown[] else not any[];
}

while a bit awkward, would solve the problem below, wouldn't it?

With arr is any[]:
Currently the true branch loses all type safety for elements of an array even if the element types were previously known (and makes a readonly array writable, doesn't it?)

Having the guard return arr is unknown[] breaks narrowing in the false branch for a union of SomeArray | SomeObject.

tl;dr;

I actually assigned Array.isArray to another export and redefined its typings with some overloads
to get better types out of the true branch (the more common use case), and I only use Array.isArray() when I want to assert the false branch - not an array of any type. But that still requires some care on my part that a more expressive type guard could help avoid.

//Narrows unions to those that are of array types (not 100% sure this is correct, but it's the intent).
type _ArrayCompatibleTypes<T> = T extends readonly any[] ? T : never;
// If<Pred, Then, Else> and IsNever<T> are some utility types that do what they sound like.
type ArrayCompatibleTypes<T> = If<IsNever<_ArrayCompatibleTypes<T>>, T & readonly unknown[], _ArrayCompatibleTypes<T>>;

function isArray<T extends ArrayCompatibleTypes<any>>(obj: T): obj is ArrayCompatibleTypes<T>;
function isArray<TItem>(obj: Iterable<TItem> | null | undefined): obj is TItem[];
function isArray(obj: any): obj is unknown[];

@taj-codaio
Copy link

I've found several scenarios in coding where I have roughly this pattern:

class BaseClass {
  type: SomeEnum;
}

class ChildClass extends BaseClass {
  isCurrentlyActionable: boolean;
  takeAction() {
    doSomething();
  }
}

function isChildClass(item: BaseClass): item is ChildClass {
  return item.type === SomeEnum.ChildType;
}

function canTakeAction(item: BaseClass): boolean {
  if (!isChildClass(item)) {
    return false;
  }
  return item.isCurrentlyActionable;
}

Now, there are a number of places where I need to call canTakeAction on some BaseClass item where I do not yet know the type. I find myself littering the code with this awkwardness, comment and all:

// Putting the redundant isChildClass() check only to satisfy TypeScript
if (!canTakeAction(item) || !isChildClass(item)) {
  return;
}
// Now start using item like it's a ChildClass, such as:
item.takeAction();

One alternative to the redundant check is I can just cast the item after the if block. Not really much better than the typecheck above.

Another alternative is to naively set the return type of canTakeAction to be item is ChildClass. That works well for this exact scenario, but I'll be in bad shape when I get to the scenario:

const childClass: ChildClass = new ChildClass(...);
if (canTakeAction(childClass)) {
  ...
} else {
  // childClass is now of type never :(
}

So, for now, we just litter the code with the redundant checks. I actually haven't found myself needing the negative part of the type guard scenario as far as I can remember. I just need the positive side.

@MKRhere
Copy link

MKRhere commented Apr 19, 2020

We'd also benefit from either weak type guards or one-sided guards. Our type guard library has this exact issue where if you extend the builtin types with validators, you either lose type information or it becomes unsafe.

This is safe:

const Message = struct({ from: string, to: string, date: is(Date), content: string });

declare const x: any;

if (Message(x)) {
	// x is { from: string, to: string, date: Date, content: string }
} else {
	// x is any
}

This is unsafe:

const Positive = refinement(number, x => x > 0);

declare const x: number | string;

if (Positive(x)) {
	// if we preserved guards, x is number
	// otherwise we lose validated type information
} else {
	// if we preserved guards, x would be string, which is very wrong
}

With one-sided guards, we'd be able to un-guard the else branch so runtype would be safe to use with custom validators.

@forivall
Copy link

forivall commented Nov 18, 2023

To me, since this is a mirror of the existing conditional types syntax, it might be useful to use it here too. Following is my syntax proposal, starting from the original issue proposal's "else" type guard, and taking on some tangents:

The following would be equivalent:

function isCool(value: any): boolean { /* ... */ }
function isCool(value: any): true ? value is any : value is any { /* ... */ }

And the following would narrow either side of the conditional independently:

let x: number | string = getNumberOrString();

// Narrows only the true side of the conditional
function isInteger(value: any): true ? value is number : value is unknown { /* ... */ }

if (isInteger(x)) {
  // x: number
} else {
  // x: number | string
}

// Narrows only the false side of the conditional
function isNotInteger(value: any): true ? value is unknown : value is number { /* ... */ }

if (isNotInteger(x)) {
  // x: number | string
} else {
  // x: number
}

For typechecking, the type of the return value must be the widened type of all of the literal types in the condition. In this case, since we're using a boolean literal, the else condition is Exclude<boolean, true>, ie, false.

Expanding further

This syntax has the added benefit of handling any literal primitive type so that type narrowing can be more expressive in switch statements or literal conditionals: Allow return values of true/false, 0, 1, other number literals, 'strings', undefined, null, enums to play a role in type guards.

For example, wrapping typeof in a function with this kind of type guard would look something like this:

function typeofAsAFunction(value: any): 'bigint'
  ? value is bigint
  : 'boolean'
  ? value is boolean
  : 'function'
  ? value is Function
  : 'number'
  ? value is number
  : 'object'
  ? value is object | null
  : 'string'
  ? value is string
  : 'symbol'
  ? value is symbol
  : 'undefined'
  ? value is undefined
  : value is never {
  return typeof value;
}

Note that the value is never syntax means that the return type of the function must be "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function". If the last clause was value is unknown, the return type of the function would be string.

Alternative, more concise syntax

Alternatively, move the value is outside of the conditional like the following

function typeofAsAFunction(value: any): value is (
  'bigint'
    ? bigint
    : 'boolean'
    ? boolean
    : 'function'
    ? Function
    : 'number'
    ? number
    : 'object'
    ? object | null
    : 'string'
    ? string
    : 'symbol'
    ? symbol
    : 'undefined'
    ? undefined
    : never
  ) {
  return typeof value;
}

A regular boolean conditional could be

// Narrows only the true side of the conditional
function isInteger(value: any): value is true ? number : unknown { /* ... */ }

I would expect most style guides to mandate parentheses in this case though, so it's a little clearer. Or, instead of leaving that up to style guides, make it a restriction in the language itself. (which could simplify parsing; this restriction already exists with types like A | (() => A))

// Narrows only the true side of the conditional
function isInteger(value: any): value is (true ? number : unknown) { /* ... */ }

If there's a need to express the behaviour of classic / symmetric type guards, I think the following syntax would be equivalent:

function isFoo(x: any): x is Foo { /* ... */ }
function isFoo(x: any): true ? x is Foo : x is Exclude<typeof x, Foo> { /* ... */ }
// or, this would just require an explicit template type, since `typeof` would work differently here compared to everywhere else
function isFoo<T>(x: T): true ? x is Foo : x is Exclude<T, Foo> { /* ... */ }

@MichalMarsalek
Copy link

It'd be good to collect some more use cases here.

The main objection from the design meeting was that once there are two different kinds of type guards, there's an additional cognitive load for people to choose one or the other correctly.

These one-sided typeguards are easier to infer than the two-sided one. As a result users would often not have to choose and could instead rely on ts.

@MichalMarsalek
Copy link

MichalMarsalek commented Feb 23, 2024

In Typescript,

function tg(x: any) x is T { }

means that if tg(x) is true, then x is of type T and if tg(x) is false, then x is not of type T.
I think that if typeguards are to be generalised, the negation in the false branch should be preserved to stay consistent. I'm not proposing any syntax, but something like

function tg(x: any) x is T1,T2 { }

should mean that if tg(x) is true, then x is of type T1 and if tg(x) is false, then x is not of type T2.

facebook-github-bot pushed a commit to facebook/flow that referenced this issue Apr 26, 2024
Summary:
We will be adding a qualifier to type guard definition to express the notion of a "one-sided" refinement (see [relevant TS issue](microsoft/TypeScript#15048)). The new syntax will be:
```
function foo(x: T): implies x is R { ... }
```
A one-sided type guard will only refine the then-branch of a conditional.

We are adding this feature to unblock stricter [consistency checking](https://flow.org/en/docs/types/type-guards/#predicate-type-is-consistent-with-refined-type) for the else case of default type guards (two-sided). One-sided type guards continue to have the existing consistency checking. See this exchange for more context: https://twitter.com/danvdk/status/1765745099554668830.

This diff adds AST support.

Changelog: [internal]

Reviewed By: SamChou19815

Differential Revision: D56506513

fbshipit-source-id: fb2adb11ca184bbf983973fa4d7369c5aa5f7cdb
@nathan-chappell

This comment was marked as off-topic.

@krryan
Copy link

krryan commented May 31, 2024

@nathan-chappell Being able to narrow foo while also returning foo.foo is a separate concern unrelated to this issue. I believe there is a proposal for something along those lines, but this isn’t it.

@nathan-chappell
Copy link

@krryan Sorry, I must have posted this in the wrong place. I was trying to return a value other than boolean from a typeguard, and one of the related issues must have pointed here (and I ended up here accidentally).

@ethanresnick
Copy link
Contributor

ethanresnick commented Jul 1, 2024

I would love to see this, and the use case I've had is something like this:

type Thing = A | B | C
type A = { kind: 'A', id: string, /* ... */ }
type B = { kind: 'B', id: string, /* ... */ }
type C = { kind: 'C', id: string, /* ... */ }

declare const things: Thing[];

// would love for this to infer `A | undefined`, rather than `Thing | undefined`
const theRightThing = things.find(it => it.kind === 'A' && it.id == desiredId); 

// Similarly, if we could make it handle type variables, even better...
async function findBy<T extends Thing['kind']>(criteria: { kind: T; id: string }) {
  const things = await readThingsFromSomewhere();
  return things.find(it => it.kind === criteria.kind && it.id == criteria.id);
}

@ryami333
Copy link

ryami333 commented Jul 1, 2024

@ethanresnick you can do that as of Typescript 5.5:

-const theRightThing = things.find(it => it.kind === 'A' && it.id == desiredId);
+const theRightThing = things.filter(it => it.kind === 'A').find(it => it.id == desiredId);

The type-predicate is correctly inferred in this case because it satisfies the following rules (quote from the release notes):

  1. The function does not have an explicit return type or type predicate annotation.
  2. The function has a single return statement and no implicit returns.
  3. The function does not mutate its parameter.
  4. The function returns a boolean expression that’s tied to a refinement on the parameter.

In short, we might need to get used to splitting up logical expressions into chained .filter+.find calls, but it does work now.

@ethanresnick
Copy link
Contributor

@ryami333 Thanks, but the whole point of this issue is to not need to split it like that (and doing that split obviously has runtime performance costs, in addition to arguably-worse readability).

@ethanresnick
Copy link
Contributor

@ryami333 The function I passed to find() in my example — it => it.kind === 'A' && it.id == desiredId — would be a one-sided type guard in the sense that, if the function returns true, then the input argument is definitely of type A but, if the function returns false, the input might still be an A (i.e., isn't necessarily not an A)

@MichalMarsalek
Copy link

I'm sorry but that's not the point of this issue at all - your comment does not have anything to do with "one-sided" type-guard at all. Let's get back on topic.

This is exactly the point of the issue as demonstrated by the usecase by @ethanresnick

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Awaiting More Feedback This means we'd like to hear from more people who would be helped by this feature Suggestion An idea for TypeScript
Projects
None yet
Development

Successfully merging a pull request may close this issue.