#Avoid `Record<string, unknown>` after testing existence of variable object key?
1 messages · Page 1 of 1 (latest)
Here is the code:
export const requiredValidator = <Y>(
input: object,
fieldName: string,
innerValidator: (_input: unknown) => E.Either<InputValidationError, Y>,
) => {
if (fieldName in input) {
return innerValidator((input as Record<string, unknown>)[fieldName]);
}
return E.left(inputValidationError(`'${fieldName}' ${Constants.VALIDATION_ERROR_MESSAGES.NOT_VALID}`));
};
as Record<string, unknown> feels.... dirty.
why not input: Partial<Record<string, unknown>>?
Oh, interesting. And I don't even need to prove to the TS type checker that input is a Partial<Record<string, unknown>>, as long as it is an object. That's perfect.
Thanks!
But then why doesn't the TS checker directly allow input[fieldName] when input is only known as an object?
object doesn't imply there are any keys
whereas Record<string, unknown> does
In that case, can assigning an object to a Partial<Record<string, unknown>> ever cause type-related problems that are not caught by the TS checker?
for reading, its perfectly safe of course
objects can all be indexed by any string, at runtime
it's just that some keys will be undefined - which is what the Partial is for
I'm not quite sure its needed here actually, since unknown includes undefined
but i still do think it makes the meaning of the type clearer, if nothing else
I see.
Thanks for the extra explanation.