简体   繁体   中英

Typescript return type Interface has additional fields

I want to get data from database and return it as defined in interface (ie only values matching interface). i wrote following codes

// get data from databae - db.find() 
async getCustomerList(): Promise<CustomerInfoInterface[]> {
  const customerList = await db.find();
  return customerList;
}

AND

export interface CustomerInfoInterface {
  firstName: string;
  lastName: string;
  phone: string;
  address?: string;
  birthDate?: Date;
  data?: object;
}

When I called the function I get

[
    {
        "customerId": "5d63b80ce186984f50617c95",
        "phone": "+9475588752",
        "firstName": "Jhon",
        "lastName": "Doe",
        "address": "No. 1, Some Rd, Somewhere",
        "birthDate": "1990-01-01",
        "data": {},
        "secret1": "a-efw53.0",
        "secret2": "b-45300"
    },
    {
        ...
]

But I expect to get a response exactly matching the interface. (error if less or filter more). What is the problem here and how is it implemented using interfaces?

ps: I know I can do the above thing by manually mapping each value but intention here is using Interfaces .

I'm working on Loopback 4 on ubuntu (TypeScript)

It's not possible to do with Interface s only. It's compile time information. There're no interfaces in runtime. To achieve what you want, there're should be physical values available for mapping. Eg array of prop names. And you have to do this yourself (or use libs like lodash) to filter only needed props.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM