Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Is it possible to refer to a property of a type? #3867

Closed
philippotto opened this issue May 3, 2017 · 2 comments
Closed

Is it possible to refer to a property of a type? #3867

philippotto opened this issue May 3, 2017 · 2 comments

Comments

@philippotto
Copy link

philippotto commented May 3, 2017

I would like to write a generic setter function which receives the property name as a string and the property value as type T which should conform to the type determined by the property name.

Something like this would be nice:

/* @flow */

type t = {
  a: string,
  b: number,
}

const obj: t = {
  a: "hi",
  b: 1,
};

// Syntax error since t[k] doesn't work
function change<k: $Keys<t>>(key: k, value: t[k]) {
  obj[key] = value;
}

change("a", "...");
change("b", 1324);
change("b", "..."); // should fail

Is there a way to achieve this?

@agentcooper
Copy link
Contributor

I've never actually used it, but probably $PropertyType is the thing you want: https://flow.org/en/docs/types/utilities/#toc-propertytype.

@philippotto
Copy link
Author

Thanks for the pointer! I had looked through the utilities, but apparently I overlooked this.

However, I guess, I have to wait until $PropertyType allows the second parameter to be a non-string. Since this is sort of tracked in #2310, I'll close this issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants