求教这种typescript对象类型如何转数组?

已知一个有很多属性的对象:

const a = {
    test1: 1,
    test2: 2
    ...
}

如何定义一个键值对应的数组?

[
  {
      key: 'test1',
      value: 1
  },
  {
      key: 'test2',
      value: 2
  }
]

尝试之后key: 'test1'总是能对上value: 2 ...
求助大佬!

阅读 2.4k
2 个回答
type KeyValuePair = {
  key: string;
  value: number;
};


const a = {
  test1: 1,
  test2: 2,
  // ...
};

const result: KeyValuePair[] = Object.entries(a).map(([key, value]) => ({
  key,
  value: value as number,
}));

console.log(result);
type A = {
    test1: 1;
    test2: 2;
};
const a: A = {
    test1: 1,
    test2: 2,
};
type C<T> = {
    key: keyof T;
    value: T[keyof T];
};
let arr: C<A>[] = [
    {
        key: "test1",
        value: 1,
    },
    {
        key: "test2",
        value: 2,
    },
];
logo
Microsoft
子站问答
访问
宣传栏