Reputation: 4615
I'm trying to get the DataType(?) from string input value.
const data = ['1', 'hello', '[]', '{key: [value]}', '`2020-10-08`'];
function funct(data: string): DataType {
if(??) {
return Object
} else if(??) {
return Number
} else if(??) {
return Array
} else if (??) {
return Date
}
return String
}
data.map((d) => console.log(funct(data)));
// Number, String, Array, Object, Data
function funct(d) {
if(d.startsWith('{') && d.endsWith('}')) {
return typeof {}
} else if(d.indexOf('-') !== -1 && !isNaN(Date.parse(d))) {
return 'Date';
} else if(!isNaN(parseFloat(d))) {
return typeof 1
} else if(d.startsWith('[') && d.endsWith(']')) {
return typeof []
} else return typeof 'string'
}
console.log('number', funct('1'));
console.log('number', funct('123'));
console.log('string', funct('`as2d`'));
console.log('string', funct('2s2d'));
console.log('Object', funct('{}'));
console.log('Array', funct('[]')); //object :(
console.log('Array', funct('["d", "f"]')); //object :(
Upvotes: 0
Views: 1007
Reputation: 2702
You can try something like this:
function funct(d) {
if(d.startsWith('{') && d.endsWith('}')) {
return Object
} else if(d.indexOf('-') !== -1 && !isNaN(Date.parse(d))) {
return Date;
} else if(!isNaN(parseFloat(d))) {
return Number
} else if(d.startsWith('[') && d.endsWith(']')) {
return Array
} else return String
}
Note: this was tested in JS so, I removed the type annotations. Please them if you want to compile it in TypeScript.
Upvotes: 1