admin管理员组

文章数量:1330564

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

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

Share Improve this question asked Aug 10, 2017 at 11:36 dmnsgndmnsgn 4041 gold badge13 silver badges28 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 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.

本文标签: javascriptTypescript spread interface keys as union of stringsStack Overflow