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

Expose "set object key" in a utility type? #4794

Closed
mkscrg opened this issue Sep 4, 2017 · 1 comment
Closed

Expose "set object key" in a utility type? #4794

mkscrg opened this issue Sep 4, 2017 · 1 comment

Comments

@mkscrg
Copy link

mkscrg commented Sep 4, 2017

Flow understands when a new key is added to an object:

const o = { foo: 'hello' };
o.bar = 42;
console.log(o.bar); // all good! Flow knows about the key `bar`

But (AFAIK) it's impossible to write a well-typed generic function for setting a key. It might work if we exposed a $SetKey utility:

function setProp<O: {}, K: string, V>(o: O, k: K, v: V): $SetKey<O, K, V> {
  return { ...o, [k]: v };
}

Thoughts? Am I missing something, and this is actually possible today?

Background

I'd like to define types for a binary parsing library with syntax like

const p = new Parser()
  .int16("id")
  .nullTermString("name");

const b = Buffer.from([ 0x04, 0xD2, 0x46, 0x6C, 0x6F, 0x77, 0x00 ]);
console.log(p.parse(b)); // { id: 1234, name: 'Flow' }

But this requires using string literals as keys in object types, e.g.

declare class Parser<T: {}> {
  int16<K: string>(k: K): Parser<$SetKey<T, K, number>>;
  nullTermString<K: string>(k: K): Parser<$SetKey<T, K, string>>;
}
@madbence
Copy link

madbence commented Sep 4, 2017

@mkscrg O & { [K]: V } should work, but right now K is always string, even if you pass a string literal to setProp, so it becomes O & { [string: V } which is not very useful 😿

maybe (?) see #2639 #4175 #4748

@SamChou19815 SamChou19815 closed this as not planned Won't fix, can't repro, duplicate, stale May 18, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants