Skip to content

Commit 5adf1cc

Browse files
feat(macro): make select macro choices strictly typed
1 parent d77d6c1 commit 5adf1cc

File tree

2 files changed

+24
-6
lines changed

2 files changed

+24
-6
lines changed

packages/core/macro/__typetests__/index.test-d.tsx

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -266,7 +266,9 @@ expectType<string>(
266266
//// Select
267267
///////////////////
268268

269-
const gender = "male"
269+
type Gender = "male" | "female" | "other"
270+
const gender = "male" as Gender // make the type less specific on purpose
271+
270272
expectType<string>(
271273
select(gender, {
272274
// todo: here is inconsistency between jsx macro and js.
@@ -280,6 +282,21 @@ expectType<string>(
280282
})
281283
)
282284

285+
expectType<string>(
286+
// @ts-expect-error: missing required property
287+
select(gender, {
288+
male: "he",
289+
other: "they",
290+
})
291+
)
292+
293+
expectType<string>(
294+
select(gender, {
295+
// @ts-expect-error extra properties are not allowed
296+
incorrect: "",
297+
})
298+
)
299+
283300
expectType<string>(
284301
// @ts-expect-error value could be strings only
285302
select(5, {

packages/core/macro/index.d.ts

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -154,10 +154,11 @@ export function selectOrdinal(
154154
options: ChoiceOptions
155155
): string
156156

157-
type SelectOptions = {
157+
type SelectOptions<T extends string> = {
158158
/** Catch-all option */
159159
other: string
160-
[matches: string]: string
160+
} & {
161+
[key in T]: string
161162
}
162163

163164
/**
@@ -180,9 +181,9 @@ type SelectOptions = {
180181
* @param value The key of choices to use
181182
* @param choices
182183
*/
183-
export function select(
184-
value: string | LabeledExpression<string>,
185-
choices: SelectOptions
184+
export function select<T extends string>(
185+
value: T | LabeledExpression<T>,
186+
choices: SelectOptions<T>
186187
): string
187188

188189
/**

0 commit comments

Comments
 (0)