Abdul Razzaq
Abdul Razzaq

Reputation: 115

How to exclude a property type from an array of classes in Typescript

Is it possible in typescript to deeply remove a prop from a class in an array nested in another class? this way for example:

class Nested {
  propX!: string;
  propY!: string;
  propZ!: string;
}

class Parent {
  propA!: string;
  propB!: number;
  propC!: string;
  nesteds!: Nested[]; 
}

// remove propZ from nesteds in Parrant class
class ParentInput implement Exclude<Parent, 'propC'|'nesteds.propZ'> {
  //...
}


Upvotes: 1

Views: 985

Answers (1)

Connor Low
Connor Low

Reputation: 7186

You can use Pick and Exclude to filter out properties. Since Nested is, well, nested, you'll have to use extra type declarations to get it working:

// Grab every property except for 'propZ' out of Nested.
//   This is optional: you can just use `Pick<Nested...` directly below.
type FilteredNested = Pick<Nested, Exclude<keyof Nested, 'propZ'>>

// Grab every property except for 'propC' and 'nesteds' from Parent, 
//   then intersect a new `nesteds` definition using the above type
type FilteredParent = Pick<Parent, Exclude<keyof Parent, 'propC' | 'nesteds' >> & {
    nesteds: FilteredNested[]
}

class ParentInput implements FilteredParent {
    nesteds!: FilteredNested[];
    propA!: string;
    propB!: number;
}

Full Playground

Upvotes: 1

Related Questions