Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP: Improve type narrowing for .includes #75

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
50 changes: 50 additions & 0 deletions src/tests/array-includes.ts
Expand Up @@ -59,6 +59,47 @@ doNotExecute(async () => {
}
});

doNotExecute(async () => {
/**
* type narrowing for numbers in readonly array
*/
let arr = [1, 2, 3] as const;

let member = 1 as 1 | 2 | 4;
if (arr.includes(member)) {
type tests = [Expect<Equal<typeof member, 1 | 2>>];
}
});

doNotExecute(async () => {
/**
* type narrowing for objects in readonly array
*/
const arr = [{ a: 1 }, { a: 2 }, { a: 3 }] as const;

arr.includes(
// @ts-expect-error
4,
);

let member = { a: 1 } as const;
if (arr.includes(member)) {
type tests = [Expect<Equal<typeof member, { a: 1 }>>];
}
});

doNotExecute(async () => {
/**
* type narrowing for objects in writable array
*/
let arr: Array<1 | 2 | 3> = [1, 2, 3];

let member = 1 as 1 | 2 | 4;
if (arr.includes(member)) {
type tests = [Expect<Equal<typeof member, 1 | 2>>];
}
});

doNotExecute(async () => {
const arr: Array<"1" | "2" | "3"> = ["1", "2", "3"];

Expand All @@ -73,3 +114,12 @@ doNotExecute(async () => {
true,
);
});

doNotExecute(async () => {
const arr: Array<1 | 2 | 3> = [1, 2, 3];

let member = 4 as 3 | 4;
if (arr.includes(member)) {
type tests = [Expect<Equal<typeof member, 3 | 4>>];
}
});