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

Strict mode #10

Open
eliassjogreen opened this issue Sep 16, 2024 · 0 comments
Open

Strict mode #10

eliassjogreen opened this issue Sep 16, 2024 · 0 comments
Labels
enhancement New feature or request

Comments

@eliassjogreen
Copy link
Member

eliassjogreen commented Sep 16, 2024

An idea would be to add a "strict" mode, which errors when you are violating the types of said endpoint.

It would use a generic in the type definition like following:

function fetch<T>("/api/path", ...);

Which could then, conditionally be enabled in places where it is desired as following:

fetch<Strict>("/api/path");

// This is expected to error with TS2345:
// > Argument of type '"/api/path/which/doesnt/exist"' is not assignable to parameter of type '"/api/path"'.
fetch<Strict>("/api/path/which/doesnt/exist");

// This would also be expected to error if the request init isn't as specified:
// > Type '{ ... }' is missing the following properties from type '{ ... }'
fetch<Strict>("/api/path", { ... });

This would also be entirely opt-in due to the nature of TypeScript and when we can trigger the error without overwriting the base fetch type.

Flags

I suggest we add two (three?) new flags:

  1. --only-strict - Enables TypeFetch types only when the strict generic is satisfied, e.g. does not set a generic default. (function fetch<T>)
  2. --optional-strict - Greedily enables TypeFetch types when the parameters match a specified operation. Strict mode can be enforced by setting the generic but it has a default value so gets matched by default anyways. (function fetch<T = ...>)
  3. ? --no-strict - Disables the strict generic entirely. (function fetch)

Open to suggestions about how these should be named and described, I am not sure that "strict" is the best way to describe it nor that they should be separate flags. Perhaps a --strictness=<none|lax|strict> is better considering the exclusiveness of the option?

PS

I just had a thought: What if we make the type parameter extend the path of the operation. E.g. fetch<T extends `/api/path`>(input: T, ...). That way we get strict type checking when it does not have a default set and if the --optional-strict flag is set it behaves lazily instead.

@eliassjogreen eliassjogreen added the enhancement New feature or request label Sep 16, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant