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

Properly infer the type for a given match #3

Open
ythecombinator opened this issue Feb 7, 2022 · 0 comments
Open

Properly infer the type for a given match #3

ythecombinator opened this issue Feb 7, 2022 · 0 comments
Labels
bug Something isn't working

Comments

@ythecombinator
Copy link
Owner

ythecombinator commented Feb 7, 2022

Description

Given this sample interface:

declare let fetchState:
  | { status: "loading" }
  | { status: "success"; data: string }
  | { status: "error" };

We could have switch-based braching:

export default function MyComponent() {
  return (
    <div>
      {(() => {
        switch (fetchState.status) {
          case "loading":
            return <p>Loading</p>;
          case "success":
            return <p>{fetchState.data}</p>;
          case "error":
            return <p>Oops</p>;
        }
      })()}
    </div>
  );
}

In order to be able to replace this snippet with our library, ie.:

export default function MyComponent() {
  return (
      <Match value={fetchState}>
        <With status="loading">
          <p>Loading</p>
        </With>
        <With status="success">
          <p>{fetchState.data}</p>
        </With>
        <With status="error">
          <p>Oops</p>
        </With>
        <Otherwise>Fallback</Otherwise>
      </Match>
  );
}

we'd need to ensure that when status is success, data exists. Instead, an error is thrown:

Property 'data' does not exist on type 'FetchState'.
  Property 'data' does not exist on type '{ status: "loading"; }'.ts(2339)

Probably, this should be addressed with some narrowing strategy (like type-predicates).

Resources

@ythecombinator ythecombinator added the bug Something isn't working label Feb 7, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

1 participant