2017-08-10 57 views
2

的工会是否有可能进行类型检查函数参数是interface的关键之一:打字稿蔓延`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(' | ')

回答

2

是,您可以:

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

+0

完美。可用,因为:TypeScript 2.1 – dmnsgn