fny fny - 1 year ago 148
TypeScript Question

Convert Property Types in Transformation

I have an array of raw data similar to the following with an interface for a corresponding type I want to use in my application:

const rawData = [
id: 122314,
friends: 'A,B,C'
id: 23342,
friends: 'B,C'
id: 412,
friends: 'B,C'

interface DataElement {
id: number
friends: string[]

Note the real data set has about 15 other fields that I'd like to keep in place.

How can I go about transforming the raw data into the typed data? Everything I've tried so far ends up with a type error about
not matching
, since the types on friends obviously conflict.

Answer Source

Something along the lines of:

 const elts: DataElement[] = rawData.map(d => Object.assign({},d,{friends: d.friends.split(',')}) as DataElement)

The Object.assign is to avoid mutating rawData during the transformation. If you don't mind, it can be shorter

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download