#Avoid `Record<string, unknown>` after testing existence of variable object key?

1 messages · Page 1 of 1 (latest)

dark zodiac
#

Is there a way to avoid the as Record<string, unknown> in this case?

#

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.

fast nova
#

why not input: Partial<Record<string, unknown>>?

dark zodiac
#

Thanks!

dark zodiac
#

But then why doesn't the TS checker directly allow input[fieldName] when input is only known as an object?

fast nova
#

whereas Record<string, unknown> does

dark zodiac
#

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?

fast nova
#

yes, if you mutate it

#

not sure if adding a Readonly<> will fix that

fast nova
#

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

dark zodiac
#

I see.

dark zodiac
#

Thanks for the extra explanation.