Skip to content

Commit

Permalink
Make String.startsWith return ${P}${string}
Browse files Browse the repository at this point in the history
  • Loading branch information
alexgleason committed Aug 10, 2023
1 parent 4d44ea0 commit 2d790a3
Show file tree
Hide file tree
Showing 4 changed files with 44 additions and 0 deletions.
5 changes: 5 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,11 @@
"types": "./dist/array-index-of.d.ts",
"import": "./dist/array-index-of.mjs",
"default": "./dist/array-index-of.js"
},
"./string-starts-with": {
"types": "./dist/string-starts-with.d.ts",
"import": "./dist/string-starts-with.mjs",
"default": "./dist/string-starts-with.js"
}
},
"keywords": [],
Expand Down
1 change: 1 addition & 0 deletions src/entrypoints/recommended.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@
/// <reference path="set-has.d.ts" />
/// <reference path="map-has.d.ts" />
/// <reference path="array-index-of.d.ts" />
/// <reference path="string-starts-with.d.ts" />
9 changes: 9 additions & 0 deletions src/entrypoints/string-starts-with.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
interface String {
/**
* Returns true if the sequence of elements of searchString converted to a String is the
* same as the corresponding elements of this object (converted to a String) starting at
* position. Otherwise returns false.
*/
startsWith<P extends string>(searchString: P): this is `${P}${string}`;
startsWith<P extends string>(searchString: P, position: 0): this is `${P}${string}`;
}
29 changes: 29 additions & 0 deletions src/tests/string-starts-with.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { doNotExecute, Equal, Expect, ExpectFalse } from "./utils";

doNotExecute(() => {
const str: string = '#hashtag';

if (str.startsWith('#')) {
type tests = [Expect<Equal<typeof str, `#${string}`>>];
};

if (str.startsWith('#', 0)) {
type tests = [Expect<Equal<typeof str, `#${string}`>>];
};

if (str.startsWith('#', 1)) {
type tests = [
ExpectFalse<Equal<typeof str, `#${string}`>>,
Expect<Equal<typeof str, string>>,
];
};
});

doNotExecute(() => {
const str = '#hashtag' as const;

if (str.startsWith('#')) {
// type does not narrow
type tests = [Expect<Equal<typeof str, '#hashtag'>>];
};
});

0 comments on commit 2d790a3

Please sign in to comment.