I am working with an object that has a const assertion:
const foo = {
bar: ['a', 'b'],
} as const;
My objective is to create a function that can update the bar
array and accurately infer the new type.
I have successfully achieved this by passing foo.bar
into the function:
type Bar = Readonly<string[]>;
function update<T extends Bar>(arr: T) {
return {
bar: [...arr, 'c'],
} as const;
}
const updatedFoo = update(foo.bar);
// The inferred type is:
//
// const updatedFoo: {
// readonly bar: readonly ["a", "b", "c"];
// }
However, when I try to pass in the entire foo
object, I encounter issues:
type Foo = Readonly<{ bar: Bar }>;
function update2<T extends Foo>(obj: T) {
return {
bar: [...obj.bar, 'c'],
} as const;
}
const updatedFoo2 = update2(foo);
// The inferred type becomes too wide:
//
// const updatedFoo2: {
// readonly bar: readonly [...string[], "c"];
// }
I am seeking guidance on how to revise the update2
function to correctly infer the type of bar
as
readonly ["a", "b", "c"]
.