Reputation: 5569
I have a User
object:
type User = {
name: string,
};
That has a get()
function, that takes in parameter the key of an attribute on User
and returns this attribute.
The function get is
User.prototype.get = (prop) => {
return this[prop];
};
How can I write this fonction definition ? Here's what I got so far:
type User = {
name: string,
get: (k: $Keys<User>) => any, // How can I change any to the correct property type ?
};
Upvotes: 1
Views: 160
Reputation: 5569
Seems like you can use now $ElementType<T, K>
.
To be confirmed !
Source: 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
Upvotes: 1