Skip to content

Commit 66b5678

Browse files
committed
Change types to work as a type guard
1 parent 9020a64 commit 66b5678

File tree

3 files changed

+31
-4
lines changed

3 files changed

+31
-4
lines changed

index.test-d.ts

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import type {Element, Root, RootContent} from 'hast'
2+
import {expectAssignable, expectType} from 'tsd'
3+
import {hasProperty} from './index.js'
4+
5+
const aWithTitle = (function (): Root | RootContent {
6+
return {type: 'element', tagName: 'a', properties: {title: 'a'}, children: []}
7+
})()
8+
9+
if (hasProperty(aWithTitle, 'title')) {
10+
expectAssignable<Element>(aWithTitle)
11+
expectType<
12+
Element & {
13+
properties: Record<
14+
'title',
15+
Array<number | string> | number | string | true
16+
>
17+
}
18+
>(aWithTitle)
19+
expectType<Array<number | string> | number | string | true>(
20+
aWithTitle.properties.title
21+
)
22+
}

lib/index.js

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
/**
2+
* @typedef {import('hast').Element} Element
23
* @typedef {import('hast').Nodes} Nodes
34
*/
45

@@ -7,17 +8,20 @@ const own = {}.hasOwnProperty
78
/**
89
* Check if `node` is an element and has a `name` property.
910
*
11+
* @template {string} Key
12+
* Type of key.
1013
* @param {Nodes} node
1114
* Node to check (typically `Element`).
12-
* @param {string} name
15+
* @param {Key} name
1316
* Property name to check.
14-
* @returns {boolean}
17+
* @returns {node is Element & {properties: Record<Key, Array<number | string> | number | string | true>}}}
1518
* Whether `node` is an element that has a `name` property.
19+
*
20+
* Note: see <https://github.com/DefinitelyTyped/DefinitelyTyped/blob/27c9274/types/hast/index.d.ts#L37C29-L37C98>.
1621
*/
1722
export function hasProperty(node, name) {
1823
const value =
1924
node.type === 'element' &&
20-
node.properties &&
2125
own.call(node.properties, name) &&
2226
node.properties[name]
2327

package.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,13 +42,14 @@
4242
"prettier": "^3.0.0",
4343
"remark-cli": "^11.0.0",
4444
"remark-preset-wooorm": "^9.0.0",
45+
"tsd": "^0.28.0",
4546
"type-coverage": "^2.0.0",
4647
"typescript": "^5.0.0",
4748
"xo": "^0.55.0"
4849
},
4950
"scripts": {
5051
"prepack": "npm run build && npm run format",
51-
"build": "tsc --build --clean && tsc --build && type-coverage",
52+
"build": "tsc --build --clean && tsc --build && type-coverage && tsd",
5253
"format": "remark . -qfo && prettier . -w --log-level warn && xo --fix",
5354
"test-api": "node --conditions development test.js",
5455
"test-coverage": "c8 --100 --reporter lcov npm run test-api",

0 commit comments

Comments
 (0)