Home > Enterprise >  Typescript: what is a typesafe way to detect if an optional property exists
Typescript: what is a typesafe way to detect if an optional property exists

Time:12-04

consider the following ...

interface UpdateCustomerInput {
  customerId: string
  name?: string
  age?: number
  admin?:  boolean
}

function updateCustomer(input: UpdateCustomerInput) {

   let customer = await getManager().findOneOrFail(Customer, input.customerId)

    if ('name' in input) {
      customer.name = input.name
    }

    if ('age' in input) {
      customer.age = input.age
    }

    if ('admin' in input) {
      customer.admin = input.admin
    }

    return getManager().save(Customer, customer)
}

I really do not like the non-typesafe condition check if (string in object).

The logic needs to handle if a boolean property is set to false or a numeric property is set to 0.

What is the best typesafe way of doing this check. Does a util method exist somewhere - or is their a nice one the community can recommend?

CodePudding user response:

The fastest way to check if an optional property is defined or not is to check if its undefined. When an optional property is not defined, and you try to retrieve it from an object, your object will be undefined. So you can translate your code like this:

interface UpdateCustomerInput {
  customerId: string
  name?: string
  age?: number
  admin?:  boolean
}

function updateCustomer(input: UpdateCustomerInput) {

   let customer = await getManager().findOneOrFail(Customer, input.customerId)

    if (input.name!==undefined) {
      customer.name = input.name
    }

    if (input.age!==undefined) {
      customer.age = input.age
    }

    if (input.admin!==undefined) {
      customer.admin = input.admin
    }

    return getManager().save(Customer, customer)
}
  • Related