#Best way to get ts to infer a returned object with string literal keys
29 messages · Page 1 of 1 (latest)
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>
OH hah yeah that's right I forgot about just type returns lol
Oh not really, it lets you give invalid keys
I rarely write those because ts is usually pretty good for this
const sample5 = (x:number): Record<`sample_${number}`, string> => ({
[`XYZ_${x}`]: "Hello"
})
const result5 = sample5(1)
// ^? - const result5: Record<`sample_${number}`, string>
Yeah the type return is safer
try changing the sample string
see this
Oh weird
I guess it is some safety still
why does that happen
report it
But yeah I guess that's the only way currently?
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
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
I'm pro "add as many tests/confirmations as possible". But you're welcome to do it as you wish 🙂