Skip to content

Strict mode #10

@eliassjogreen

Description

@eliassjogreen

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions