0

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

  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?

  • Force assigning a type doesn't mutate an object, it just indicates to TS that it should treat the value *as if* it were that type. In your case TS does adhere to the new type — `products[0].isVisible` will error as expected even though the object might actually have that property. [playground](https://tsplay.dev/mAd3kN) – pilchard Jan 14 '23 at 13:37
  • i see, but i there a way to actualy mutate an object? – Dmytro Afanasiev Jan 14 '23 at 13:42
  • 1
    Sure, [How do I remove a key from a JavaScript object?](https://stackoverflow.com/questions/3455405/how-do-i-remove-a-key-from-a-javascript-object). Or you could `map` after your filter `.map(({isVisible, ...product})=> product)` – pilchard Jan 14 '23 at 13:43
  • But your `filter()` call actually doesn't make sense. Filter expects a boolean as return, so to filter only products that aren't visible you would simply `.filter((product) => !product.isVisible)` – pilchard Jan 14 '23 at 13:47
  • Yes, but i thought there was a way to someshow automate this process. I wonder if it can detect redundant keys by itself and delete them. – Dmytro Afanasiev Jan 14 '23 at 13:48
  • No, you'll need to implement that yourself. – pilchard Jan 14 '23 at 13:50
  • ok, that thing with 'map' looks good, thank you – Dmytro Afanasiev Jan 14 '23 at 13:53

1 Answers1

2

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.

mseyfayi
  • 116
  • 5