Home > Blockchain >  Typescript define type for method argument
Typescript define type for method argument

Time:02-26

I have a company object, that looks like this:

{ 
 tracking_hours: {
  open: '8:00',
  close: '20:00'
 }
}

I use it to set values this way:

set({
 openTime: setTime(company, 'open_time'),
 closeTime: setTime(company, 'close_time'),
})

I need somehow set a type for company in setTime function

export function setTime(
    company: {
        tracking_hours: null | any
    },
    type: string,
): number | null {
    if (company.tracking_hours) {
        if (company.tracking_hours[type]) {
            const time = Number(company.tracking_hours[type].split(':')[0])

            if (time) {
                return time
            } else {
                return null
            }
        }

        return null
    }

    return null
}

How can I replace any with its actual type?

CodePudding user response:

This can be done by

  • Creating a separate type for the Company
  • Using keyof to indicate the correct type for type
const company = {
  tracking_hours: {
    open: "8:00",
    close: "20:00",
  },
};

interface Company {
  tracking_hours: {
    open: string;
    close: string;
  };
}

function setTime(
  company: Company,
  type: keyof Company["tracking_hours"]
): number | null {
  const time = Number(company.tracking_hours[type].split(":")[0]);

  return time ?? null
}

setTime(company, "open");
setTime(company, "close");

Note, I've simplified some of your code because

  • You don't need to check for the presence of company.tracking_hours or company.tracking_hours[type] - TypeScript guarantees it will they will always be present because of the types that have been specified in the function signature
  • You only need to return null once, since all the other cases would have dropped out of the respective blocks and hit the final return statement anyway.
  • Related