It can be challenging to pinpoint this precisely as it hinges on the typing of your variables such as key1
.
To determine the typeof values in keyArray
, we use (typeof keyArray)[number]
and establish a type with those types as keys and string
as the respective value:
type FromKeys = Record<(typeof keyArray)[number], string>
However, the key type pertains to the type of key1
, not the actual value. If the type of key1
is a string literal, this aligns with what you need. Yet, if the type is simply string
, then the FromKeys
type will permit any string
property, rendering it less practical.
type FromKeys<T extends readonly PropertyKey[]> = Record<T[number], string>
declare function makeObject<T extends readonly PropertyKey[]>(keyArray: T): FromKeys<T>;
const obj1 = makeObject(["a", "b", "c"]); // Record<string, string>
const obj2 = makeObject(["a", "b", "c"] as const); // Record<"a" | "b" | "c", string>
Playground Link