Skip to content

Commit

Permalink
Change types to work as a type guard
Browse files Browse the repository at this point in the history
  • Loading branch information
wooorm committed Aug 1, 2023
1 parent 9020a64 commit 66b5678
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 4 deletions.
22 changes: 22 additions & 0 deletions index.test-d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import type {Element, Root, RootContent} from 'hast'
import {expectAssignable, expectType} from 'tsd'
import {hasProperty} from './index.js'

const aWithTitle = (function (): Root | RootContent {
return {type: 'element', tagName: 'a', properties: {title: 'a'}, children: []}
})()

if (hasProperty(aWithTitle, 'title')) {
expectAssignable<Element>(aWithTitle)
expectType<
Element & {
properties: Record<
'title',
Array<number | string> | number | string | true
>
}
>(aWithTitle)
expectType<Array<number | string> | number | string | true>(
aWithTitle.properties.title
)
}
10 changes: 7 additions & 3 deletions lib/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
/**
* @typedef {import('hast').Element} Element
* @typedef {import('hast').Nodes} Nodes
*/

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

Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,13 +42,14 @@
"prettier": "^3.0.0",
"remark-cli": "^11.0.0",
"remark-preset-wooorm": "^9.0.0",
"tsd": "^0.28.0",
"type-coverage": "^2.0.0",
"typescript": "^5.0.0",
"xo": "^0.55.0"
},
"scripts": {
"prepack": "npm run build && npm run format",
"build": "tsc --build --clean && tsc --build && type-coverage",
"build": "tsc --build --clean && tsc --build && type-coverage && tsd",
"format": "remark . -qfo && prettier . -w --log-level warn && xo --fix",
"test-api": "node --conditions development test.js",
"test-coverage": "c8 --100 --reporter lcov npm run test-api",
Expand Down

0 comments on commit 66b5678

Please sign in to comment.