-
-
Notifications
You must be signed in to change notification settings - Fork 8
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
type TestFunction is a type predicate, not a generic predicate #15
Comments
@chmac Using a TS Predicate ensures that when used with a conditional, inside the unist-util-is/unist-util-is-test.ts Lines 36 to 37 in 8c0a649
unist-util-is/unist-util-is-test.ts Lines 72 to 76 in 8c0a649
coming into this function, TypeScript only knows In your example try: import { Node, Parent } from "unist";
import visit from "unist-util-visit";
export const insertBefore = (
tree: Parent,
predicate: (node: Node, index?: number, parent?: Parent) => node is Node,
transform: (node: Node) => Node
) => {
visit(tree, predicate, (node, index, parent) => {});
}; or even better import { Node, Parent } from "unist";
import { Test } from "unist-util-is";
import visit from "unist-util-visit";
export const insertBefore = <T extends Node>(
tree: Parent,
predicate: Test<T>,
transform: (node: T) => Node
) => {
visit(tree, predicate, (node, index, parent) => {});
}; Also reference the type tests in https://github.com/syntax-tree/unist-util-visit/blob/master/types/unist-util-visit-tests.ts for more examples. |
@ChristianMurphy I don't think I've 100% grok'd this yet, but will spend some more time on it. Thanks for the detailed explanation. It seems like you made a reasoned decision which I misunderstood. What about adding something to the docs sharing how to use this package in TypeScript? I'd be happy to have a go at submitting a PR to that effect if that would be helpful. |
More documentation is welcome. Types like |
If I understand this conversation correctly, I believe I can close this. |
Subject of the issue
I'm looking at this:
unist-util-is/index.d.ts
Lines 29 to 33 in 8c0a649
As I read the docs, and the code, the test is "converted" here:
unist-util-is/convert.js
Lines 18 to 20 in 8c0a649
As I understand the docs I can have a function that tests the content of the node and returns
boolean
whether the node is a match for my conditions or not.However, as I read the types, my function must be a type predicate that asserts whether or not my node is of a given TypeScript type.
I'm definitely not a TypeScript expert, so I may have gotten something wrong here. If so, apologies. If not, I can try to add an additional type test.
Your environment
v 4.0.1
Steps to reproduce
Expected behaviour
I believe that my example above would run in javascript, but fails type checking.
Actual behaviour
The text was updated successfully, but these errors were encountered: