Reputation: 641
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?
Upvotes: 0
Views: 27
Reputation: 4651
This can be done by
Company
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
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 signaturereturn null
once, since all the other cases would have dropped out of the respective blocks and hit the final return statement anyway.Upvotes: 1