Skip to content

Instantly share code, notes, and snippets.

@fmnoise
Forked from mfikes/README.md
Created August 21, 2018 08:41
Show Gist options
  • Save fmnoise/239b6689d71054fd0099d04efd17c5f6 to your computer and use it in GitHub Desktop.
Save fmnoise/239b6689d71054fd0099d04efd17c5f6 to your computer and use it in GitHub Desktop.
Seeing the inferred type of a ClojureScript expression

If you are curious about the types inferred by ClojureScript, it is easy to get some insight using a macro:

(defmacro inferred-type [form]
  `'~(cljs.analyzer/infer-tag &env
       (cljs.analyzer/no-warn (cljs.analyzer/analyze &env form))))

This is the kind of dev-time macro you could refer using the new user.cljs feature.

This gist sets this macro up along with a REPL, running in ClojureScript master:

clj -Srepro -Sdeps '{:deps {github-mfikes/gist-3837f510aad3e8ff766eb9071ef66b2b {:git/url "https://gist.github.com/mfikes/3837f510aad3e8ff766eb9071ef66b2b" :sha "be8efccb8fb6a0a04dbfdc52e572766ca495ec0b"}}}' -m cljs.main -co @compile-opts.edn -re node -r

Here is an example of using it:

cljs.user=> (inferred-type 1)
number
cljs.user=> (inferred-type "a")
string
cljs.user=> (inferred-type (if x 1 "a"))
#{number string}

Checking an inferred type inside an expression:

cljs.user=> (let [x (+ 2 3)]
  (inferred-type x))
number

You can even see the new function return type inference in action:

cljs.user=> (defn foo [x]
  (cond
    (pos? x) "a"
    (neg? x) 3
    :else true))
#'cljs.user/foo
cljs.user=> (inferred-type (foo 1))
#{boolean number string}
{:repl-requires [[cljs.repl :refer [doc source pst]]
[type-utils :refer [inferred-type]]]
:warnings {:single-segment-namespace false}}
{:paths ["."]
:deps {org.clojure/clojurescript {:git/url "https://github.com/clojure/clojurescript" :sha "81a1ea127974d43a6166fbdae33bcaa296fe9156"}}}
(ns type-utils)
(defmacro inferred-type [form]
`'~(cljs.analyzer/infer-tag &env
(cljs.analyzer/no-warn (cljs.analyzer/analyze &env form))))
(ns type-utils
(:require-macros [type-utils]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment