Skip to content

[Lit/Task]: Improve type-checking by using const #4829

@maxpatiiuk

Description

@maxpatiiuk

Should this be an RFC?

  • This is not a substantial change

Which package is this a feature request for?

Task (@lit/task)

Description

TypeScript 5.0 added the const modifier for type variables.

It can be adapted in@lit/task like so:

export class Task<
-  T extends ReadonlyArray<unknown> = ReadonlyArray<unknown>,
+  const T extends ReadonlyArray<unknown> = ReadonlyArray<unknown>,
-  R = unknown,
+  const R = unknown,
 > {

The advantage of this is that argument types and return types would be inferred better by TypeScript. Example:

// Before this was inferred as Task<(string | undefined)[], string[]>
// With addition of "const" it would be Task<readonly [string | undefined], readonly [string]> - a much more accurate type
  _dataTask = new Task(
    this,
    async ([name]) => {
      if (name === undefined) {
        return "";
      }

      const response = await fetch(`example.com/${name}`);
      return [await response.text()];
    },
    () => [this.name],
  );

Alternatives and Workarounds

If const is not included in the @lit/tasks typings, it can be manually included in the component source code:

-    () => [this.name],
+    () => [this.name] as const,

however, not every TypeScript user would be aware of this, so some might get frustrated by bad type checking experience when using Lit Task

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    Status

    ✅ Done

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions