Skip to content

Commit e018f7d

Browse files
committed
feat: add const type parameter to isLiteralOneOf
Enable literal type inference without 'as const' assertion by using TypeScript 5.0+ const type parameters. This maintains full backward compatibility while improving developer experience.
1 parent 6ad122d commit e018f7d

File tree

3 files changed

+19
-2
lines changed

3 files changed

+19
-2
lines changed

deno.jsonc

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,11 @@
44
"compilerOptions": {
55
"exactOptionalPropertyTypes": true
66
},
7+
"lint": {
8+
"rules": {
9+
"exclude": ["no-import-prefix"]
10+
}
11+
},
712
"exports": {
813
".": "./mod.ts",
914
"./as": "./as/mod.ts",

is/literal_one_of.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,14 +12,14 @@ import type { Predicate, Primitive } from "../type.ts";
1212
* ```ts
1313
* import { is } from "@core/unknownutil";
1414
*
15-
* const isMyType = is.LiteralOneOf(["hello", "world"] as const);
15+
* const isMyType = is.LiteralOneOf(["hello", "world"]);
1616
* const a: unknown = "hello";
1717
* if (isMyType(a)) {
1818
* const _: "hello" | "world" = a;
1919
* }
2020
* ```
2121
*/
22-
export function isLiteralOneOf<T extends readonly Primitive[]>(
22+
export function isLiteralOneOf<const T extends readonly Primitive[]>(
2323
literals: T,
2424
): Predicate<T[number]> {
2525
const s = new Set(literals);

is/literal_one_of_test.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,4 +28,16 @@ Deno.test("isLiteralOneOf<T>", async (t) => {
2828
assertType<IsExact<typeof a, "hello" | "world">>(true);
2929
}
3030
});
31+
32+
await t.step("works without as const assertion", () => {
33+
const predicate = isLiteralOneOf(["foo", "bar"]);
34+
assertEquals(predicate("foo"), true);
35+
assertEquals(predicate("bar"), true);
36+
assertEquals(predicate("baz"), false);
37+
38+
const b: unknown = "foo";
39+
if (predicate(b)) {
40+
assertType<IsExact<typeof b, "foo" | "bar">>(true);
41+
}
42+
});
3143
});

0 commit comments

Comments
 (0)