0

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?

3
  • tracking_hours: null | { open: string, close: string }? Commented Feb 25, 2022 at 12:38
  • @VLAZ TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ open: string; close: string; }'.   No index signature with a parameter of type 'string' was found on type '{ open: string; close: string; }'. Commented Feb 25, 2022 at 12:41
  • So, what do you want to do, exactly? Allow any strings for keys of tracking_hours or restrict the values of type to be the kets of tracking_hours? Or something else? Note that right now you're passing in "open_hours" for type but the key found on the object is open. Commented Feb 25, 2022 at 12:47

1 Answer 1

1

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.
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.