-1

例如,如果我有这个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"`

这是重现该问题的示例。

任何帮助将不胜感激,谢谢。

更新:找到一篇与此问题相关的精彩文章。

4

1 回答 1

1

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

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

于 2021-04-24T20:47:36.397 回答