简体   繁体   English

typescript:从 object 中获取密钥 map 与通用

[英]typescript: get an key map from object with generic

I want to get the key map from any object,我想从任何 object 中获取密钥 map,

I've implemented the function,我已经实现了 function,

but I can't make typescript happy,但我不能让 typescript 高兴,

what should I do without using acc: any如果不使用acc: any

const origin = {
  a: 1,
  b: 'string',
  c: () => {}
};

function getObjKeyMap<T>(obj: T) {
  return Object.keys(obj).reduce((acc, k) => {
 /* Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'.
  No index signature with a parameter of type 'string' was found on type '{}'.ts(7053) */
    acc[k] = k;
    return acc;
  }, {});
}

const keyMap = getObjKeyMap(origin);

You need to tell the type of object that reduce uses for accumulator.您需要告诉 object 的类型,以reduce用于蓄电池的用途。

const originObj = {
  a: 1,
  b: 'string',
  c: () => {}
};

function getObjKeyMap<T>(obj: T) {
  return Object.keys(obj).reduce((acc, k) => {
    acc[k] = k;
    return acc;
  }, {} as Record<string, string>);
}

// or


function getObjKeyMap1<T>(obj: T) {
  return Object.keys(obj).reduce((acc: Record<string, string>, k: string) => {
    acc[k] = k;
    return acc;
  }, {});
}

const keyMap = getObjKeyMap(originObj);

TS Playground TS游乐场

However, I bet this is not the best solution.但是,我敢打赌这不是最好的解决方案。 I bet there is a way to write a function declaration like this:我敢打赌,有一种方法可以像这样编写 function 声明:

function getObjKeyMap<T, K extends keyof T>(obj: T): Record<K, K>

Where Typescript automatically tells you that getObjectMap({a: 1, b: 'string', c: () => {}} returns {a: "a", b: "b", c: "c"} . Where Typescript automatically tells you that getObjectMap({a: 1, b: 'string', c: () => {}} returns {a: "a", b: "b", c: "c"} .

I think this is much better:我认为这要好得多:

const originObj = {
  a: 1,
  b: 'string',
  c: () => {}
};

type KeyMap<T> = {
  [key in keyof T]: key
};

function getObjKeyMap<T>(obj: T): KeyMap<T> {
  return Object.keys(obj).reduce((acc, k) => ({...acc, k: k}), {} as KeyMap<T>);
}


const keyMap = getObjKeyMap<typeof originObj>(originObj);

TS Playground TS游乐场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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