2017-06-06 18 views
1

objを私がUserオブジェクトを有する:FlowType:関数の戻り値のタイプ(K)=> [K]

type User = { 
    name: string, 
}; 

パラメータでUser戻るの属性のキーをとるget()機能を有していますこの属性。 関数getが、私はこのfonction定義を書くことができますどのように

User.prototype.get = (prop) => { 
    return this[prop]; 
}; 

はありますか?ここ は、私がこれまでに得たものです:あなたが今$ElementType<T, K>を使用することができるように

type User = { 
    name: string, 
    get: (k: $Keys<User>) => any, // How can I change any to the correct property type ? 
}; 
+0

期待されるタイプとは何ですか? 'string'ですか? 'age:number'プロパティを' User'に追加すると、それは 'string |数字? –

+0

はい。しかし戻り値の型は 'obj [prop]'の戻り型でなければなりません。より正確に型チェックできます – whitep4nther

+0

'name'と 'number'で呼ばれると期待される型は 'string' 'この種の動的な型付けがFlowで可能かどうかわかりません – whitep4nther

答えて

0

は思えます。 確認してください!

出典:https://github.com/facebook/flow/issues/4122#issuecomment-314700605


EDIT:Working example

/* @flow */ 

type User = { 
    name: string, 
    age: number, 
} 

const user: User = { 
    name: 'Ilyes', 
    age: 21, 
} 

function get<K: string>(key: K): $ElementType<User, K> { 
    return user[key]; 
} 

const number: number = get('name'); // error 
const number2: number = get('age'); // works 
const string: string = get('name'); // works 
const string2: string = get('age'); // error 
関連する問題