#Why does this not return Record<string,string>?

20 messages · Page 1 of 1 (latest)

distant nexus
#
wicked juncoBOT
#

@distant nexus Here's a shortened URL of your playground link! You can remove the full link from your message.

SpicyMikeX#9109

Preview:```ts
export function validateRequestString(
validationObject: Record<string, string | unknown>
): Record<string, string> {
for (const key of Object.keys(validationObject)) {
const value = validationObject[key]

if (typeof value !== "string") {
  throw new Error(
    `Exp

...```

distant nexus
#

Is there a way have typescript infer Record<string,string> after doing this validation function?

wanton torrent
wanton torrent
distant nexus
#

That makes sense. Okay thanks for your help!

#

How... do I resolve this thread

wicked juncoBOT
wanton torrent
#

!ts

wicked juncoBOT
#
export function validateRequestString(
  validationObject: Record<string, string | unknown>
): Record<string, string> {
  return Object.fromEntries(Object.entries(validationObject).map(([k, v]) => {
    if (typeof v !== 'string') {
      throw new Error(
        `Expected ${k} to be of type string, but received ${typeof v}`
      );
    }
    if (v.length === 0) {
      throw new Error(`Expected length of ${k} to be greater than 0`);
    }
    return [k, v] as const;
  }));
}```
wanton torrent
#

!resolve

wicked juncoBOT
#

@distant nexus
Because your issue seemed to be resolved, this post was marked as resolved by @wanton torrent.
If your issue is not resolved, you can reopen this post by running !reopen.
If you have a different question, make a new post in #1057653400046674112.

distant nexus
#

Thank you!!

wanton torrent
#

you likely want to just do a return obj as Record<string, string> instead

#

or as unknown as Record<string, string>

distant nexus
#

Oh yeah return as might be better...

wanton torrent
#

optionally with a comment explaining why it's safe

distant nexus
#

That's actually a much better idea instead of rebuilding an object.