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?

7
  • 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 Commented Jan 14, 2023 at 13:37
  • i see, but i there a way to actualy mutate an object? Commented Jan 14, 2023 at 13:42
  • 1
    Sure, How do I remove a key from a JavaScript object?. Or you could map after your filter .map(({isVisible, ...product})=> product) Commented Jan 14, 2023 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) Commented Jan 14, 2023 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. Commented Jan 14, 2023 at 13:48

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.