0

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
  • Hello, if it is possible to create a live example of the problem that you can link to (for example, on sqlfiddle.com or jsbin.com) then do so - but also copy the code into the question itself. Not everyone can access external sites, and the links may break over time. Use Stack Snippets to make a live demo of inline JavaScript / HTML / CSS. source: stackoverflow.com/help/how-to-ask Thanks ! Commented Apr 24, 2021 at 20:48

1 Answer 1

2

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)[]

Sign up to request clarification or add additional context in comments.

1 Comment

the problem was that, the keyof User[] is trying to get the keys of User Array, not the keys of User object. that's why the () make the work correct, thank you very much

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.