简体   繁体   中英

Typescript create object with properties with given keys

Here is simplified case what i am struggling.

 const createObj = <T extends string>(keys: T[]) => {
  return Object.fromEntries(
   keys.map((key) => [key, 0])
  );
 };

const result = createObj(["hi","hello","gg"] as const)

I hoped the result type would be {hi: 0, hello: 0, gg: 0 } but the result is any ;

you can do it in this way:

function createObj<T extends string>(arr: T[]): Record<T, number> {
  let result = {} as Record<T, number>;

  arr.forEach((x, i) => {
    result[x] = i;
  })

  return result
}


const object = createObj(["hi","hello","gg"])

Playground

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM