You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardexpand all lines: packages/lit-dev-content/site/docs/v3/data/task.md
+38
Original file line number
Diff line number
Diff line change
@@ -442,3 +442,41 @@ class MyElement extends LitElement {
442
442
```
443
443
444
444
{% 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
+
classMyElementextendsLitElement {
452
+
@property() myNumber =10;
453
+
@property() myText ="Hello world";
454
+
455
+
_myTask =newTask(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.
0 commit comments