Casting type in JavaScript

Example:

function action(value) {
     // I want to operate on a string
     String(value)...;
}

      

When we pass the dynamic values in the primary types of JavaScript ( String

, Number

, Boolean

, Object

etc.), we can (in the absence of a better word) to transfer the value of the specified type.

Is it possible to build this function in custom types and how can I do it?

An example of what I would like to do:

function action(value) {
    Point(value)...;
    // Value at this point (excuse the pun) is a point
    // // *** Would like to see that intellisense is aware of the type at this point, but please don't assume this is ONLY for intellisense***
}

      

Is it possible to call constructor functions this way and force the constructor function to "distinguish" the value to the instance itself - or does this only work for basic JavaScript types?

+3


source to share


2 answers


A custom constructor can simply examine the typeof

arguments it passed and behave accordingly. This is not technically a "cast", but rather writing code to learn the types of the arguments and then deciding on the correct behavior, which might involve converting from one type to another.

See How to overload functions in javascript? for a longer description of how to parse arguments sent to any function and then adjust the behavior of the function based on the type and position and the presence of the arguments. This same functionality can be used to make something that is "cast" (although we usually don't think about casting in Javascript, but rather just converting).

We could provide real-world examples if you can elaborate on what types you want to "distinguish" in your Point constructor.

There are some simple examples of "great" things:



function delay(fn, t) {
    // if t is passed as a string represeantation of a number, 
    // convert it to an actual number
    return setTimeout(fn, +t);
}

      


Or, a slightly more interesting example that can take a few ms, a line with ones at the end, or an object with properties:

function delay(fn, t) {
    var typeT = typeof t, ms, matches, num, multiplier,
        suffixes = {ms: 1, sec: 1000, min: 1000 * 60, hr: 1000 * 60 * 60};
    if (typeT === "string") {
        matches = t.match(/^([\d.]+)(.+)$/);
        if (matches) {
            num = +matches[1];
            multiplier = suffixes[matches[2]];
            if (multiplier) {
                ms = num * multiplier;
            }
        }
    } else if (typeT === "number") {
        // plain number is milliseconds
        ms = t;
    } else if (typeT === "object" && t.units && t.value) {
        multiplier = suffixes[t.units];
        if (multiplier) {
           ms = t.value * multiplier;
        }            
    }
    if (ms === undefined) {
        throw new Error("Invalid time argument for delay()");
    }
    return setTimeout(fn, ms);
}


delay(myFn, "2.5hr");
delay(myFn, "25sec");
delay(myFn, 150);
delay(myFn, {units: "sec", value: 25});

      

+3


source


If you are serious about the type of coercion (and there are many good reasons) ... and you want to keep using Javascript ... you might want to try TypeScript

It provides type checking and compilation to Javascript Which gives you the ability to publish TypeScript for native compilation ...

Or if you want a little for your job (like me) ... you can develop a project and spit out Javascript before loading ... at this point you can optimize the "thing" ... pass Linter, a Minifier and Obfuscator ... and you will end up with a very optimized and slightly protected piece of code (if we're talking client side, of course no obfuscation is reported on the server side).



Another benefit of BIG-BIG-BIG (at least for me) is that you can use the best Intellitype / Intellisense / Refactor IDE (VS 2013R4 CE) which is free.

See the latest features in TypeScript ... TypeScript in Build / 2014 by Anders Hejlsberg (channel9)

ZEE

+1


source







All Articles