#Explanation Required: get keyof indexed signature

6 messages · Page 1 of 1 (latest)

tough crescent
#

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?

#

I also tried
. to freeze the input beforehand
. use as const
. use readonly in SchemaInput

frank kernel
#

not because of the index signature, but because of the type annotation removing specific type info

#

use satisfies instead, in const input = { foo: "bar" } satisfies SchemaInput

tough crescent
#

😲
I see
thanks a lot

frank kernel