【问题标题】:Typescript spread `interface` keys as union of strings打字稿将“接口”键作为字符串的联合传播
【发布时间】:2018-01-18 15:21:27
【问题描述】:

是否可以将函数参数类型检查为interface 的键之一:

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

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

我希望 'id' | 'email' | 'password' 不被硬编码。

以 JS 方式,例如。 IUser 是一个对象,我可以把它翻译成 Object.keys(IUser).join(' | ')

【问题讨论】:

    标签: javascript typescript interface properties


    【解决方案1】:

    是的,你可以:

    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
    

    更多信息here

    【讨论】:

    • 完美。从以下版本可用:TypeScript 2.1
    猜你喜欢
    • 2017-09-16
    • 1970-01-01
    • 2018-12-07
    • 2021-08-22
    • 2018-04-28
    • 2021-06-20
    • 2021-08-03
    • 1970-01-01
    相关资源
    最近更新 更多