打字稿:keyof类型问题

Typescript: keyof type issue

例如,如果我有这个 User 型号:

export interface User {
  firstName: string;
  lastName: string;
  age: number;
  password: string;
  id: number;
}

并尝试 运行 此代码:

let user = {
  firstName: 'string',
  lastName: 'string',
  age: 24,
  password: 'string',
  id: 0
}

let keys: keyof User[] = Object.keys(user) as keyof User[]; // this DOES NOT WORK

// keys: UserKeys[] = Object.keys(user) as UserKeys[];  // this works 

type UserKeys = keyof User;

我收到这个错误:

Conversion of type `string[]` to type `number | keyof User[]` may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
  Type `string[]` is not comparable to type `"includes"`

这里是重现问题的 an example

如有任何帮助,我们将不胜感激。

更新: 找到了与此问题相关的 great article

let keys: (keyof User)[] = Object.keys(this.user) as (keyof User)[];

问题是 keyof User[] 不同于 UserKeys[]。虽然它与 (keyof User)[]

相同