-
-
Notifications
You must be signed in to change notification settings - Fork 5
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
👍 Add isIncludeIn
#32
Conversation
Blocked by #33 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What is the advantage of this isIncludeIn
function over isOneOf
? It seems the function is useless for object or array while it compoare values with SameValueZero algorithm?
The purpose of this function is to check the type of the Union type Enum that consists mainly of strings. import is, { type Predicate } from "./is.ts";
export type Enum = "foo" | "bar" | "baz";
// Implement as `IncludeIn`
export const isEnum: Predicate<Enum> = is.IncludeIn(
["foo", "bar", "baz"] as const,
);
const value: unknown = "foo";
if (isEnum(value)) {
const _: Enum = value;
}
// Same thing as `OneOf`
export const isEnumByOneOf: Predicate<Enum> = is.OneOf([
(x: unknown): x is "foo" => x === "foo",
(x: unknown): x is "bar" => x === "bar",
(x: unknown): x is "baz" => x === "baz",
]);
// Same thing without library
export const isEnumByJS: Predicate<Enum> = (x: unknown): x is Enum =>
["foo", "bar", "baz"].includes(x as string); |
The following are some of the disadvantages of
Therefore, if you are assuming a Union type Enum, one of the following would be better
What do you think? |
I want it to be a function that takes an array of literal values. type Primitive =
| null
| undefined
| string
| number
| boolean
| symbol
| bigint;
function isLiteralOf<T extends readonly Primitive[]>(literals: T): Predicate<T[number]>; |
Does TypeScript support a literal type of null, undefined, symbol, or bigint? If not, T must not contain those I think. |
Typescript (and JavaScript, of course) treats null, undefined, symbol, or bigint as primitives. |
Yes but my wondering is a bit different. I'm wondering that what about "literal types" in TypeScript. https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#literal-types As long as we define |
How about naming it |
It makes sense but does it useful? What that function is for? (I'm asking because I want to keep a function responsibilities as small as possible.) |
Close due to #35 |
A convenience function that defines a union type enum.