I am facing a problem while trying to convert a string to a number. I have an age
property in my JsType
which is of type number
, but I’m mapping an array of JsonType
, which has a property age
of type number
:
interface JsType{
name: string
age?: number
//... more fields
}
interface JsonType{
name: string
age?: string
//... more fields
}
const filterData: JsType[] = [{name: 'magnus'}, {name:'hikaru',age: "50"}].map((item: JsonType): JsType => {
//item.age is of type string, i want it to be of type number
let age: number | null = item.age ? Number(item.age):null
let obj = {...(age?{age}:{}) }
const doc = { ...item, ...obj }
return doc
//ts error
// Types of property 'age' are incompatible.
// Type 'string | number | undefined' is not assignable to type 'number | undefined'.
// Type 'string' is not assignable to type 'number'.
})
The compilation error happens when returning doc
object:
Types of property 'age' are incompatible.
Type 'string | number | undefined' is not assignable to type 'number | undefined'.
Type 'string' is not assignable to type 'number'.
How can I convert the string without getting the compilation error?
Paviter Singh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
3
The solution is simple, you’re declaring a obj variable for no reason, just use this approach instead:
interface JsType{
name: string
age?: number
//... more fields
}
interface JsonType{
name: string
age?: string
//... more fields
}
const filterData: JsType[] = [{name: 'magnus'}, {name:'hikaru',age: "50.5"}].map((item: JsonType): JsType => {
let age = item.age ? Number(item.age) : undefined;
const doc = { ...item, age }
return doc
})
this should work
Your Javascript is wrong too if you want to be strict. What you try is to add age
only when it’s truthy, but you leave it in ...item
in case it for example an empty string.
So I would suggest the following (removing age
by destructuring):
interface JsType{
name: string
age?: number
//... more fields
}
interface JsonType{
name: string
age?: string
//... more fields
}
const filterData: JsType[] = [{name: 'magnus'}, {name:'hikaru',age: "50"}].map((item: JsonType): JsType => {
let age: string | undefined, out: JsType;
({age, ...out} = item);
if(age) out.age = Number(age);
return out;
})