Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/good-grapes-double.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'lit-html': patch
'lit': patch
---

Improved the type inferece of the `choose()` directive to properly restrict the case type inferred from provided value. **Note**: If this change creates a type error in your code, there must have been an unreachable case that can be removed, or the type of your `value` might be missing a valid case in the union.
4 changes: 2 additions & 2 deletions packages/lit-html/src/directives/choose.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,9 @@
* }
* ```
*/
export const choose = <T, V>(
export const choose = <T, V, K extends T = T>(
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice! Yeah this fixes the issue. Playground demo

value: T,
cases: Array<[T, () => V]>,
cases: Array<[K, () => V]>,
defaultCase?: () => V
) => {
for (const c of cases) {
Expand Down
14 changes: 14 additions & 0 deletions packages/lit-html/src/test/directives/choose_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,4 +45,18 @@ suite('choose', () => {
'C'
);
});

// Type-only regression test of https://github.com/lit/lit/issues/4220
test.skip('type-only: correctly infers type of possible cases from value', () => {
type CheckoutStep = 'register' | 'delivery' | 'payment';
const step = 'register' as CheckoutStep;
return choose(step, [
// @ts-expect-error 'test' is not assignable to 'CheckoutStep'
['test', () => 1],
// @ts-expect-error 'random' is not assignable to 'CheckoutStep'
['random', () => 2],
// This should compile fine
['register', () => 3],
]);
});
});