Skip to content

Commit

Permalink
Stumble upon some narrowing issues
Browse files Browse the repository at this point in the history
  • Loading branch information
nvie committed Feb 18, 2025
1 parent 0aa8630 commit 0610f72
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
31 changes: 31 additions & 0 deletions test-d/inference.test-d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,17 @@ function isNum(x: unknown): x is number {
return typeof x === "number";
}

function isPosNum(x: unknown): x is number {
return isNum(x) && x >= 0;
}

const x = -32 as string | number;
if (isPosNum(x)) {
x.toFixed(2); // x is number
} else {
x.length; // x is number
}

{
// partition with type predicate
const items: unknown[] = [1, 2, null, true, 0, "hi", false, -1];
Expand Down Expand Up @@ -38,3 +49,23 @@ function isNum(x: unknown): x is number {
expectType<unknown[]>(numbers);
expectType<unknown[]>(others);
}

{
// partitionN with no type predicate
const items: unknown[] = [1, 2, null, true, 0, "hi", false, -1];
const [strings, numbers, others] = partitionN(
items,
(x) => String(typeof x) === "string",
(x) => String(typeof x) === "number",
);
expectType<unknown[]>(strings);
expectType<unknown[]>(numbers);
expectType<unknown[]>(others);
}

{
const values = ["hi", 3, null, "foo", -7];
const [nums, rest] = partitionN(values, isPosNum);
expectType<number[]>(nums);
expectType<(string | number | boolean)[]>(rest);
}
9 changes: 9 additions & 0 deletions test/more-itertools.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import * as fc from "fast-check";
const isEven = (x: number) => x % 2 === 0;
const isEvenIndex = (_: unknown, index: number) => index % 2 === 0;
const isPositive = (x: number) => x >= 0;
const isPositiveNum = (x: unknown): x is number => isNum(x) && x >= 0;

function isString(value: unknown): value is string {
return typeof value === "string";
Expand Down Expand Up @@ -318,6 +319,14 @@ describe("partitionN", () => {
expect(rest).toEqual([null]);
// ^^^ (string | null)[]
});

it("partitionN retains complex rich type info", () => {
const values = ["hi", 3, null, "foo", -7];
const [nums, rest] = partitionN(values, isPositiveNum);
expect(nums).toEqual([3]);
// ^^^^ number[]
expect(rest).toEqual(["hi", null, "foo", -7]);
});
});

describe("roundrobin", () => {
Expand Down

0 comments on commit 0610f72

Please sign in to comment.