Skip to content

Commit

Permalink
fix: improve types
Browse files Browse the repository at this point in the history
  • Loading branch information
revelt committed May 3, 2022
1 parent 9157fe2 commit 53262e1
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 19 deletions.
2 changes: 2 additions & 0 deletions packages/arrayiffy-if-string/README.md
Expand Up @@ -62,4 +62,6 @@ MIT License

Copyright (c) 2010-2022 Roy Revelt and other contributors

Thanks to KRyan for types https://stackoverflow.com/a/71834598/3943954

<img src="https://codsen.com/images/png-codsen-ok.png" width="98" alt="ok" align="center"> <img src="https://codsen.com/images/png-codsen-1.png" width="148" alt="codsen" align="center"> <img src="https://codsen.com/images/png-codsen-star-small.png" width="32" alt="star" align="center">
3 changes: 2 additions & 1 deletion packages/arrayiffy-if-string/package.json
Expand Up @@ -65,7 +65,8 @@
"lect": {
"licence": {
"extras": [
""
"",
"Thanks to KRyan for types https://stackoverflow.com/a/71834598/3943954"
]
}
}
Expand Down
28 changes: 12 additions & 16 deletions packages/arrayiffy-if-string/src/main.ts
@@ -1,20 +1,16 @@
/* eslint @typescript-eslint/explicit-module-boundary-types: 0 */
type StringInABox<T> = T extends ""
? []
: string extends T
? [] | [string]
: T extends string
? [T]
: T;

// If a non-empty string is given, put it into an array.
// If an empty string is given, return an empty array.
// Bypass everything else.

// type signature overloading
function arrayiffy(something: string): [string];
function arrayiffy(something: string): [];
function arrayiffy(something: any): any {
if (typeof something === "string") {
if (something.length) {
return [something];
}
return [];
}
return something;
function arrayiffy<T>(something: T): StringInABox<T>;
function arrayiffy<T>(something: T): [] | [string] | T {
if (typeof something !== "string") return something;
if (something.length) return [something];
return [];
}

export { arrayiffy };
10 changes: 8 additions & 2 deletions packages/arrayiffy-if-string/types/index.d.ts
@@ -1,4 +1,10 @@
declare function arrayiffy(something: string): [string];
declare function arrayiffy(something: string): [];
declare type StringInABox<T> = T extends ""
? []
: string extends T
? [] | [string]
: T extends string
? [T]
: T;
declare function arrayiffy<T>(something: T): StringInABox<T>;

export { arrayiffy };

0 comments on commit 53262e1

Please sign in to comment.