say I have
type Person = {
name: string
hobbies: Array<string>
}
and then this: const people: Array<Person> = [{name: "rich", age: 28}]
how do I add age AND replace hobbies with say a different type (Array<number>
) to keep it simple
I know I can use omit
to get rid of a property or intersections to add a property but I'm struggling to work it out
Obviously this is wrong but I want something like that
type Hobbies = Array<number>
type NewPerson = Omit<Person, "hobbies"> & Hobbies & Age
const people: Array<NewPerson> = [{name: "rich", age: 28, hobbies: [1,2,3]}]
CodePudding user response:
You neet to intersect with object types that have the extra properties you want to add
type Hobbies = { numbers: Array<number>}
type NewPerson = Omit<Person, "hobbies"> & Hobbies & { age: number }
const people: Array<NewPerson> = [{name: "rich", age: 28, numbers: [1,2,3]}]
CodePudding user response:
Maybe the example below helps.
type NewPerson = Omit<Person, "hobbies"> & { hobbies: Array<number>, age: number }
const people: Array<NewPerson> = [{name: "rich", age: 28, hobbies: [1, 2, 3]}]
Use the Omit type to remove the hobbies property from the Person type and then add in the new hobbies and age properties.
CodePudding user response:
You're right you'd use Omit
and an intersection. To remove hobbies
and add age
you'd do Omit
and intersect with an object type defining age
and the new version of hobbies
:
type Person = {
name: string;
hobbies: Array<string>;
};
type NewPerson = Omit<Person, "hobbies"> & { age: number, hobbies: number[] };
const people: Array<NewPerson> = [{ name: "rich", age: 28, hobbies: [1,2,3] }];