Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript convert subtype to supertype and remove extra fields

Tags:

typescript

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.

like image 296
joshpetit Avatar asked Sep 16 '25 20:09

joshpetit


1 Answers

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">;
like image 173
yousoumar Avatar answered Sep 19 '25 12:09

yousoumar