Home > Back-end >  TypeScript convert subtype to supertype and remove extra fields
TypeScript convert subtype to supertype and remove extra fields

Time:02-23

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.

CodePudding user response:

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">;
  • Related