Typescript: keyof type issue

564 Views Asked by At

For example, if I have this User model:

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

and try to run this code:

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;

I am getting this error:

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"`

Here is an example that reproduces the problem.

Any help will be appreciated, thanks.

UPDATE: Found a great article connected with this issue.

1

There are 1 best solutions below

1
On BEST ANSWER

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

The problem is that keyof User[] is different than UserKeys[]. Though it's the same as (keyof User)[]