Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert an object to an interface with less keys in typescript

i have this interface

interface Product {
    id: string
    name: string
  }

and the one that extends it

interface AdminProduct extends Product {
    isVisible: boolean
  }

then i have this code

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  const adminProducts = (await queryByCollection('product')) as AdminProduct[]

  const products = adminProducts.filter((product) => {
    if (!product.isVisible) {
      return
    }
  }).map((product)=> product as Product) as Product[]

  return products

even though i define the return type of product when i map adminProducts array it still has the key ‘isVisible’ in it

how to convert an object to smaller interface and delete all redundant keys?

>Solution :

Typescript only presents in build time and after transpile, tsc (typescript compiler) will remove all typescript types and only javascript remains.
So can’t expect to manipulate the data by TS.
You have to do it in the javascript area:

adminProducts
   .filter((adminProduct) => adminProducts.isVisible)
   .map(({isVisible, ...product}) => product)

With this code, you will remove isVisible from your list.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading