2017-08-10 32 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