4

Is it possible to typecheck a function argument to be one of the interface's keys:

export interface IUser {
  id: string;
  email: string;
  password: string;
}

const updateUserProperty = (property: 'id' | 'email' | 'password') => e =>
  this.setState({ [property]: e.target.value });

I'd like 'id' | 'email' | 'password' not be hardcoded.

In a JS way eg. IUser being an object, I can translate that to Object.keys(IUser).join(' | ')

dmnsgn
  • 404
  • 1
  • 12
  • 27

1 Answers1

9

Yes you can:

export interface IUser {
  id: string;
  email: string;
  password: string;
}

const updateUserProperty = (property: keyof IUser) => e =>
    this.setState({ [property]: e.target.value });

updateUserProperty("sdsd"); //Error
updateUserProperty("id"); //Ok

More info here.

Amid
  • 21,508
  • 5
  • 57
  • 54