typescript 中 keyof 如何使用?

如何给Object.keys一个正确的类型

以下给出一段错误的代码

const obj:{a:any, b:any, c:any} = {
    a: null,
    b: null,
    c: null
  };
const keys:[keyof typeof obj] = Object.keys(obj);
阅读 2.8k
2 个回答
const obj = {
  a: null,
  b: null,
  c: null,
};

// Object.keys 返回 string[],需要断言成指定类型
const keys = Object.keys(obj) as Array<keyof typeof obj>;
interface Obj {
    a:any;
    b:any;
    c:any;
}
const obj:Obj = {
    a: null,
    b: null,
    c: null
  };
const keys:[keyof Obj] = Object.keys(obj);
推荐问题