Hey there,
please bear with me because I'm still a ts beginner.
My goal is to copy/validate an object literal with a function. E.g.:
type SchemaInput = {
[index: PropertyKey]: SomeUnion
}
function defineProps<Schema extends SchemaInput>(schema: Schema) {
return Object.freeze(
Object
.keys(schema)
.reduce((all, key) => {
// shenanigans
return all
}, {} as { [K in keyof Schema]: SomeResult });
)
}
Ts correctly infers the keys when the schema is passed directly or as another object literal to the function.
const output = defineProperties({
foo: 'bar' // Autocomplete works
})
console.log(output.foo); // works
const input = { foo: 'bar' }; // Autocomplete does NOT work
const output = defineProperties(input);
console.log(output.foo); // works
const input: SchemaInput = { foo: 'bar' }; // Autocomplete DOES work
const output = defineProperties(input);
output['foo'] // does work but without autocomplete
output.foo; // does NOT work => index signature
Ideally I want to use the code from the last example but unfortunately the keys are not inferred as expected (because of the indexed signature). Is there any better way to achieve this?