Skip to content

Commit fd6d144

Browse files
authored
Updates task.md to include typescript as const tip. (#1329)
1 parent f1e7a67 commit fd6d144

File tree

1 file changed

+38
-0
lines changed
  • packages/lit-dev-content/site/docs/v3/data

1 file changed

+38
-0
lines changed

packages/lit-dev-content/site/docs/v3/data/task.md

+38
Original file line numberDiff line numberDiff line change
@@ -442,3 +442,41 @@ class MyElement extends LitElement {
442442
```
443443

444444
{% endswitchable-sample %}
445+
446+
### More accurate argument types in TypeScript
447+
Task argument types can sometimes be inferred too loosely by TypeScript. This can be fixed by casting argument arrays with `as const`.
448+
Consider the following task, with two arguments.
449+
450+
```ts
451+
class MyElement extends LitElement {
452+
@property() myNumber = 10;
453+
@property() myText = "Hello world";
454+
455+
_myTask = new Task(this, {
456+
args: () => [this.myNumber, this.myText],
457+
task: ([number, text]) => {
458+
// implementation omitted
459+
}
460+
});
461+
}
462+
```
463+
464+
As written, the type of the argument list to the task function is inferred as `Array<number | string>`.
465+
466+
But ideally this would be typed as a tuple `[number, string]` because the size and position of the args is fixed.
467+
468+
The return value of `args` can be written as `args: () => [this.myNumber, this.myText] as const`, which will result in a tuple type for the args list to the `task` function.
469+
470+
```ts
471+
class MyElement extends LitElement {
472+
@property() myNumber = 10;
473+
@property() myText = "Hello world";
474+
475+
_myTask = new Task(this, {
476+
args: () => [this.myNumber, this.myText] as const,
477+
task: ([number, text]) => {
478+
// implementation omitted
479+
}
480+
});
481+
}
482+
```

0 commit comments

Comments
 (0)