提取属性名称的安全方法 [英] Safe way to extract property names

查看:46
本文介绍了提取属性名称的安全方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种通过类型检查来获取对象属性名称的方法,该方法可以在重构后捕获可能的回归.

I'm looking for a way to get an object property name with typechecking that allows to catch possible regressions after refactoring.

这是一个示例:必须将属性名称作为字符串传递的组件,如果我尝试更改模型中的属性名称,它将被破坏.

Here's an example: the component where I have to pass the property names as strings and it will be broken if I'll try to change the property names in the model.

interface User {
   name: string;
   email: string;
}

class View extends React.Component<any, User> {

   constructor() {
      super();
      this.state = { name: "name", email: "email" };
   }

   private onChange = (e: React.FormEvent) => {
      let target = e.target as HTMLInputElement;
      this.state[target.id] = target.value;
      this.setState(this.state);
   }

   public render() {
      return (
         <form>
            <input
               id={"name"}
               value={this.state.name}
               onChange={this.onChange}/>
            <input
               id={"email"}
               value={this.state.email}
               onChange={this.onChange}/>
            <input type="submit" value="Send" />
         </form>
      );
   }
}

如果有解决这个问题的好方法,我将不胜感激.

I'd appreciate if there's any nice solution to solve this issue.

推荐答案

在TS 2.1中引入了keyof关键字,这使得这成为可能:

In TS 2.1 the keyof keyword was introduced which made this possible:

const propertyOf = <TObj>(name: keyof TObj) => name;

const propertiesOf = <TObj>(_obj: (TObj | undefined) = undefined) => <T extends keyof TObj>(name: T): T => name;

然后可以像这样使用它们:

These can then be used like this:

propertyOf<MyInterface>("myProperty");

const myInterfaceProperties = propertiesOf<MyInterface>();
myInterfaceProperties("myProperty");

const myInterfaceProperties = propertiesOf(myObj);
myInterfaceProperties("myProperty");

如果myProperty不是MyObj类型的属性,则会出现错误.

This will give an error if myProperty is not a property of the type MyObj.

https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-1.html

这篇关于提取属性名称的安全方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆