0

given an interface of Person i would like to create a new interface HasmapOfPersonsOverTime based on that. im gonna push updates of Person objects (i.e if a person has a birthday i will push the new age number, and the time the person celebrated the birthday as a object into the array on the age property).

... symbolizes the rest of the properties

interface Person {
    age:number;
    name:string;
    ...
}

i would like an interface looking like :

interface HasmapOfPersonsOverTime {
  [id:string]:{
    age:[
          {
            age:number
            time:string
          }
        ]
    },
    name:[
          {
            name:string
            time:string
          }
        ]
    },
    ...
}

and to give an example on how i would like to use it:

const list:HasmapOfPersonsOverTime = {
  "1515":{ 
    age:[
      {
        age:24,
        time:"2020-03-05T21:53:37"
      },
      {
        age:25,
        time:"2021-03-05T18:22:05"
      }
    ],
    name:[
      {
        name:"bar",
        time:"1996-03-05T21:53:37"
      }
    ],
    ...
  }
}

i have come this far but i cant get type safety on properties. i create "value":string where i want the correct person property.

interface Person {
  age:number;
  name:string;
}
type HasmapOfPersonsOverTime <T extends Object> = Record<string,Record<keyof T, {'value':string,'time':string}[]>>

const list: HasmapOfPersonsOverTime<Person> = {
  "1515":{ 
    age:[
      {
        value:"24",
        time:"2020-03-05T21:53:37"
      },
      {
        value:"25",
        time:"2021-03-05T18:22:05"
      }
    ],
    name:[
      {
        value:"name",
        time:"1996-03-05T21:53:37"
      }
    ]
  }
}

1 Answer 1

2

You can use the following mapped type, also used with other builtin types such as Pick

type Person = {
  age: number;
  name: string;
};

type OverTime<T> = {
  [K in keyof T]: (Pick<T, K> & { time: string })[];
};

type HashmapOfPersonOverTime = Record<string, OverTime<Person>>;
Sign up to request clarification or add additional context in comments.

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.