#Return type not assignable to Record

31 messages · Page 1 of 1 (latest)

delicate parcelBOT
#
NoSpoon#0148

Preview:```ts
type SomeType = Record<string, string>

function myFunc<
A extends SomeType,
K extends keyof A & string

(arr: A[], keys: readonly K[]): Record<K, string> {
// Do something here

ret
...```

modern blade
#

Not sure why Typescript is giving me an error even though I've explicitly returned an object with property keys conforming to Record<K, string)

solar jasper
#

keys is not typed to be all elements of K, that's impossible, and that's the important part

#

fromEntries is giving { [key: K]: string }, while Record<K, string> is [key in K]: string }
the difference is that in the latter, all of K is said to be a member, while not so in the former

modern blade
#

But even if I change the return type to Partial<Record<K, string>>, I will still get an error

#

Just to make sure I understand the problem correctly, { [key: K]: string } is an object with property keys that are a subset of K?

solar jasper
#

oh it's giving [key: string] not [key: K], misread

solar jasper
#

i suppose fromEntries loses type info like the other Object methods

modern blade
#

So are Partial<Record<K, string>> and { [key: K]: string } the same thing?

modern blade
solar jasper
#

yes, the fromEntries loses that exact type info

#

K is broadened to string

modern blade
#

Without casting the return value with as Record< K, string>, how else would I do something like Object.fromEntries without losing type info?

solar jasper
#

not sure something like that exists

modern blade
#

So I'm guessing casting it is my only option

solar jasper
#

someone else might know something

modern blade
wanton bloom
wanton bloom
#

(being unsafe is the reason why it's not the default typings)

modern blade
modern blade
wanton bloom
#
const x: (1 | 2 | 3)[] = [];
#

or rather [K, V][] may not have all the keys

modern blade
#

But it would if you're passing in a literal array?

wanton bloom
modern blade
#

True, but in my case it would still be useful and type safe since my keys are inferred from my function arguments

wanton bloom
#

except your parameters aren't literal tuples