I don't know why, but I like this ... (convert strings to other primitives)


#1

The following takes what you type and tells you if you’ve typed number

(This is in 5.0, but works with minor adjustments in 3.0 and 4.0).

    import { Component, stache, stacheConverters } from "//unpkg.com/can@5/ecosystem.mjs";

    stache.addConverter(stacheConverters);

    Component.extend({
        tag: "my-app",
        view: `
            <p>Enter a value: <input on:input:value:to="string-to-any(enteredValue)"/></p>
            <p>You've typed a(n) {{enteredType}}</p>
        `,
        ViewModel: {
            enteredValue: "any",
            get enteredType(){
                return typeof this.enteredValue;
            }
        }
    });

string-to-any will convert something like:

  • “4.4” to 4.4
  • “true” to true
  • “NaN” to NaN
  • “null” to null
  • “undefined” to undefined

Handy …