BIS Tech
BIS Tech

Reputation: 19444

how to set only specific types to the interface

address is a map. it has so many keys in the database. I didn't want to pass all keys to my other API.

export interface BookingModel {
    address: Address
}

I want to pass only these three types to API

export interface Address {
    location: string,
    flatNo: string,
    id: string
}

I pass address details like this.

{
    'addressDetails': bookingModel.address,
}

But addressDetails has all keys, not specified keys.

Upvotes: 0

Views: 53

Answers (1)

spender
spender

Reputation: 120480

You could write a pick function to prune your full-fat address down in a typesafe fashion:

const pick = <T, K extends keyof T>(obj: T, ...keys: K[]): Pick<T, K> => {
  const keySet = new Set(keys);
  return Object.fromEntries(Object.entries(obj).filter(
    ([k]) => keySet.has(k as K))) as Pick<T, K>;
}

then use it:

{
    addressDetails: pick(bookingModel.address, 'location', 'flatNo', 'id'),
}

Upvotes: 3

Related Questions