I need to pass nested object as method argument. Inline everything works, but passing variable will result in TS error because for example { a: 'x' } will become { a: string } instead. Solution for that is to use as const on that variable. But this does not work on objects with arrays etc. I'm forced to use 'as const' multiple times INSIDE that object, instead just doing 'as const` at the end. Why?
type A = 'xxx' | 'yyy' | 'zzz'
type Demo = {
a: A,
b: number,
}[]
const demoMethod = (demo: Demo) => {
console.log(demo)
}
/* Example #1 - OK */
demoMethod([
{ a: 'xxx', b: 111 },
{ a: 'yyy', b: 222 },
{ a: 'xxx', b: 333 },
])
/* Example #2 - ERROR */
const demo2 = [
{ a: 'xxx', b: 111 },
{ a: 'yyy', b: 222 },
{ a: 'xxx', b: 333 },
]
demoMethod(demo2)
/* Example #3 - OK */
const demo3 = [
{ a: 'xxx', b: 111 } as const,
{ a: 'yyy', b: 222 } as const,
{ a: 'xxx', b: 333 } as const,
]
demoMethod(demo3)
/* Example #4 - ERROR */
const demo4 = [
{ a: 'xxx', b: 111 },
{ a: 'yyy', b: 222 },
{ a: 'xxx', b: 333 },
] as const
demoMethod(demo4)
It does not make any sense for me that even that example #1 and #2 are 100% the same, #2 does not work and I'm forced to change my data using multiple 'as const' instead passing it at it is. Is there any better solution to force TS to treat my const argument same way as inline argument?
Edit: Note that I have defined type and method only in my example purposes. In real life this method comes from external package, and without exported type.