Skip to content

Commit

Permalink
Merge pull request #105 from mefechoel/main
Browse files Browse the repository at this point in the history
Add a Map.has reset with the same semantics as Set.has
  • Loading branch information
mattpocock committed Mar 8, 2023
2 parents 4e62e79 + 249945e commit 6673bc2
Show file tree
Hide file tree
Showing 5 changed files with 85 additions and 0 deletions.
5 changes: 5 additions & 0 deletions package.json
Expand Up @@ -58,6 +58,11 @@
"import": "./dist/set-has.mjs",
"default": "./dist/set-has.js"
},
"./map-has": {
"types": "./dist/map-has.d.ts",
"import": "./dist/map-has.mjs",
"default": "./dist/map-has.js"
},
"./utils": {
"types": "./dist/utils.d.ts",
"import": "./dist/utils.mjs",
Expand Down
29 changes: 29 additions & 0 deletions readme.md
Expand Up @@ -217,6 +217,35 @@ const userSet = new Set(["matt", "sofia", "waqas"] as const);
userSet.has("bryan");
```

### Make `Map.has()` less strict

```ts
import "@total-typescript/ts-reset/map-has";
```

Similar to `.includes` or `Set.has()`, `Map.has()` doesn't let you pass members that don't exist in the map's keys:

```ts
// BEFORE
const userMap = new Map([["matt", 0], ["sofia", 1], [2, "waqas"]] as const);

// Argument of type '"bryan"' is not assignable to
// parameter of type '"matt" | "sofia" | "waqas"'.
userMap.has("bryan");
```

With the rule enabled, `Map` is much smarter:

```ts
// AFTER
import "@total-typescript/ts-reset/map-has";

const userMap = new Map([["matt", 0], ["sofia", 1], [2, "waqas"]] as const);

// .has now takes a string as the argument!
userMap.has("bryan");
```

### Removing `any[]` from `Array.isArray()`

```ts
Expand Down
9 changes: 9 additions & 0 deletions src/entrypoints/map-has.d.ts
@@ -0,0 +1,9 @@
/// <reference path="utils.d.ts" />

interface Map<K, V> {
has(value: K | (TSReset.WidenLiteral<K> & {})): boolean;
}

interface ReadonlyMap<K, V> {
has(value: K | (TSReset.WidenLiteral<K> & {})): boolean;
}
1 change: 1 addition & 0 deletions src/entrypoints/recommended.d.ts
Expand Up @@ -4,3 +4,4 @@
/// <reference path="json-parse.d.ts" />
/// <reference path="array-includes.d.ts" />
/// <reference path="set-has.d.ts" />
/// <reference path="map-has.d.ts" />
41 changes: 41 additions & 0 deletions src/tests/map-has.ts
@@ -0,0 +1,41 @@
import { doNotExecute } from "./utils";

doNotExecute(() => {
const map = new Map([
[1, "1"],
[2, "2"],
[3, "3"],
] as const);

map.has(4);

map.has(
// @ts-expect-error
"4",
);

map.has(
// @ts-expect-error
true,
);
});

doNotExecute(() => {
const map = new Map([
[1, "1"],
[2, "2"],
[3, "3"],
] as const) as ReadonlyMap<1 | 2 | 3, "1" | "2" | "3">;

map.has(4);

map.has(
// @ts-expect-error
"4",
);

map.has(
// @ts-expect-error
true,
);
});

0 comments on commit 6673bc2

Please sign in to comment.