0

I have a class like this:

interface UserProps {
  name: string
  age: number
}

export class User {
  constructor(private data: UserProps) {}

  get(propName: string): number | string {
    return this.data[propName]
  }
}

and I don't know why I get this error: "Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'UserProps'.
No index signature with a parameter of type 'string' was found on type 'UserProps'
"

any advice?

1

1 Answer 1

1

Your error occurs because you can't use any string as the key, only a subset (name and age). Set keyof UserProps as the type for propName:

interface UserProps {
  name: string
  age: number
}

export class User {
  constructor(private data: UserProps) {}

  get<T extends keyof UserProps>(propName: T): UserProps[T] {
    return this.data[propName]
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

This isn't enough of an improvement, IMO - user.get("age") still returns number | string which is misleading, at the very least.
@VLAZ I think this is a good solution however I think this error should not happen.
@ehsan it's your code that is sloppy. For it to work, TS also has to be sloppy. Which causes an error. The solution is not good enough because the resulting type doesn't necessarily match what it should be. That's what I was highlighting.

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.