2

If we were to have these types:

interface Person {
  name: string;
}
interface Agent extends Person {
  code: number;
}

and have this code:

const agent: Agent = {
  name: 'name',
  code: 123
}

How would you cast the type Agent into Person and remove the code field? When I try to do this:

const person: Person = agent as Person
console.log(person) // Still contains the fields of agent

This is a simple example, but in my real usecase the object has a lot more fields. I've also tried:

person: Person = {
...agent
}

Another post I looked at that didn't work for my case: Restrict type by super class in interface.

Youssouf Oumar
  • 29,373
  • 11
  • 46
  • 65
joshpetit
  • 677
  • 6
  • 17
  • Have you seen [this question](https://stackoverflow.com/questions/50378612/how-to-cast-object-to-another-type-and-remove-unneeded-fields-in-typescript)? – David Scholz Feb 22 '22 at 13:48
  • @DavidScholz Oh wow, I did plenty of googling but didn't find that, thank you – joshpetit Feb 22 '22 at 14:08
  • If the number of extra properties of Agent is limited, you could do `const { code, ...person} = agent` – www.admiraalit.nl Feb 22 '22 at 14:41
  • @www.admiraalit.nl yea that's what I surmised I could do, but for my usecase it makes it a little impractical/annoying. I could always just do it once and create a method to do the conversions. Thank you! – joshpetit Feb 22 '22 at 14:43

1 Answers1

2

Casting doesn't mean that the real value inside what is casted will change. It is for the developper to tell TypeScript "trust me on this, I know what is inside". It makes sense only during development, not on runtime.

For the the development part, maybe Utility Types will help. You could do for example something like this (if you wanna keep some fields from Agent inside Person):

type Person = Pick<Agent, "name"|"address">;
Youssouf Oumar
  • 29,373
  • 11
  • 46
  • 65
  • I haven't seen the utility types such as pick, that's really awesome I'll likely use it in the future. Looking at the answer [here](https://stackoverflow.com/questions/50378612/how-to-cast-object-to-another-type-and-remove-unneeded-fields-in-typescript) it's not possible to remove the extra fields. Thanks a lot for the support – joshpetit Feb 22 '22 at 14:41
  • Yeah you can't with casting. And yeah Utility Types are great in some cases. Glad I could pass the info ! – Youssouf Oumar Feb 22 '22 at 14:57