#Best way to get ts to infer a returned object with string literal keys

29 messages · Page 1 of 1 (latest)

grizzled valley
#

Is sample 4 the only way to get this function to return the correct type of Record?

shy schoonerBOT
#
higherorderfunction#0

Preview:```ts
const sample1 = (x: number) => ({
[sample_${x}]: "Hello",
})
const result1 = sample1(1)
// ^?

const sample2 = (x: number) => ({
[sample_${x} as const]: "Hello",
})
const result2 = sample1(1)
// ^?

const sample3 = (x: number) =>
({
[sample_${x}]: "Hello",
...```

#
const sample5 = (x:number): Record<`sample_${number}`, string> => ({
    [`sample_${x}`]: "Hello" 
}) 
const result5 = sample5(1)
//    ^? - const result5: Record<`sample_${number}`, string>
solid laurel
#

More safety with this route

#

I think?

grizzled valley
#

OH hah yeah that's right I forgot about just type returns lol

solid laurel
#

Oh not really, it lets you give invalid keys

grizzled valley
#

I rarely write those because ts is usually pretty good for this

shy schoonerBOT
#
const sample5 = (x:number): Record<`sample_${number}`, string> => ({
    [`XYZ_${x}`]: "Hello" 
}) 
const result5 = sample5(1)
//    ^? - const result5: Record<`sample_${number}`, string>
grizzled valley
#

Yeah the type return is safer

solid laurel
#

I mean it's not safe

#

should be, but it isn't

grizzled valley
#

Maybe it's the playground because it's wrong (correct) in vscode

solid laurel
#

try changing the sample string

grizzled valley
#

Oh weird

solid laurel
#

I guess it is some safety still

grizzled valley
#

why does that happen

solid laurel
#

report it

grizzled valley
#

But yeah I guess that's the only way currently?

solid laurel
#

I think TS won't infer string literals as anything but strings

#

so yeah I believe so

#

I'm not sure, but I don't have any better ideas

#

I tend to prefer explit return type annotation anyway

grizzled valley
#

I'm always pro "let ts sort it out" unless doesn't

#

in this case it appears it does not

#

I do write the returns on util types

solid laurel
#

I'm pro "add as many tests/confirmations as possible". But you're welcome to do it as you wish 🙂