1

Here is my code:

object = {'name' : String}
object = {'age' : Number}
typeof object.name // 'function'
typeof object.age // 'function'

Is it possible to check that object.name is a String and object.age is a Number?

Using typeof only gives me back 'function'.

4
  • could you show the code that includes the typeof? Commented Nov 11, 2010 at 8:16
  • 1
    You realize String is the actual string constructor, right? If that's what you want to check, you can just do object.name == String. Commented Nov 11, 2010 at 8:17
  • i think you might be thinking in Actionscript. In Javascript, the rhs of the property is the value or instance of an object, not a type. eg var object = { name: 'geoff', age: 66 }; Commented Nov 11, 2010 at 8:21
  • At this point, you might want to look into Microsoft's TypeScript now that's it been released. Commented Oct 7, 2012 at 2:08

2 Answers 2

4

Rather than doing:

object = {'name' : String}
object = {'age' : Number}

You should check for actual data type:

object = {'name' : 'test', 'age' : 123}

And here is how you can check their type:

alert(typeof(object.name));
alert(typeof(object.age));

Output:

string
number
Sign up to request clarification or add additional context in comments.

Comments

0
var object = {
    "name" : "test",
    "age"  : 123
};

if (!isNaN(parseInt(object.age, 10))) {
    // It is a numerical value (since this is an age, an int may be appropriate)
    alert("It's numeric!");
}
if (object.name.toString() === object.name) {
    // It is really a string
    alert("It's a string!");
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.