简体   繁体   中英

How to replace types in typescript?

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]}]

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]}]

Playground Link

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] }];

Playground link

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM