I am working on a project using Typescript. The code works fine. I am just wondering what would be the best practice for the type definition of a mapped Object that has been filtered and aslo defined already. For instance, if I have the following code:
const person: Person = {
name: 'Joe',
surname: 'Doe',
age: 30,
address: [{
mainAddress: {
street: "Queen st",
number: 9,
building: 'main',
unit: 5,
},
secundaryAddress: {
street: "King st",
number: 7,
house: 'The house'
}
}]
}
interface Person {
name: string
surname: string
age: number
address: [{
mainAddress: {
street: string
number:number
building: string
unit: number
}},
{
secundaryAddress: {
street: string
number: number
house: string
}
}]
}
const filterPerson = person.address.filter((ad: any) => ad.mainAddress ? true : false)
const mappedAddress = filterPerson.map((m: any) => m.)
After I do the filter on the main Object. I need to map the result. In this case the filterPerson.map works fine with any as a type definition, but is there a best way to define ad in the filter and m in the map or should I write a new interface for both in this case.
The error that pops up if I delete any on the filter and I hover on mainAddress of the example is this
[![enter image description here][1]][1]
As you can see the Object in my code is different but the syntax on the example here is the same. [1]: https://i.stack.imgur.com/hfaro.png
You give us the below object which has
addressas an objectBut then give us this as the interface which has
addressas an array of objects.And then you give us an incomplete filter method:
Please fix your examples
EDIT: Assuming that
addressis actually defined like the below I would create 4 interfaces, one for the mainPerson, 1 for theAddressand one for each type ofAdressAnd then your
filterPersonconst can be typed as follows: