Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript spread `interface` keys as union of strings

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(' | ')

like image 875
dmnsgn Avatar asked Oct 24 '25 04:10

dmnsgn


1 Answers

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.

like image 193
Amid Avatar answered Oct 26 '25 18:10

Amid