I have a function that checks to see if a generic type’s value exists in an array:
export function isValueInArray<T extends string>(
values: T[],
value: T | undefined
) {
return value ? values.includes(value) : false;
}
It would then be used like this:
export type Status = 'OPEN' | 'CANCELED' | 'ACCEPTED' | 'INVALIDATED';
// typeof buyNowStatus === Status
const isValid = isValueInArray(['OPEN'], buyNowStatus)
In this case it works in terms of auto-completing the first array argument. The issue is that we can pass in any string:
// no typescript error is thrown here
const shouldBeInvalid = isValueInArray(['OPEN', 'ANY'], buyNowStatus)
One way to fix this would be to pass the Status in as a generic:
// ts errors out properly (but we must pass in a generic)
const isInvalid = isValueInArray<Status>(['OPEN', 'ANY'], buyNowStatus)
Is there a way to achieve this without needing to pass Status in as a generic? To somehow infer the Status type from buyNowStatus and for that to override the default T extends string behaviour in isValueInArray?
function checkStatus(status: Status) {
// no typescript error thrown here either
return isValueInArray(['ANY'], status);
}