flow icon indicating copy to clipboard operation
flow copied to clipboard

Const assertions

Open goodmind opened this issue 6 years ago • 5 comments

Proposal

https://devblogs.microsoft.com/typescript/announcing-typescript-3-4/#const-assertions

const foo = ([1, 2, 3]: const) // Type is [+1, +2, +3] (how to do read-only elements on tuple?)
const bar = ('foo': const) // Type is 'foo'
const baz = ({foo: 1}: const) // Type is '{| +foo: 1 |}'

Use case

More explicit version of https://github.com/facebook/flow/pull/7607 Also would eliminate need for Object.freeze as tool for casting to singleton strings Object.freeze is also a bit broken with regards to subtyping #7964

Not sure how sound it is, given that it is type cast essentially

Alternative

const foo = Object.freeze('foo') // Type is 'foo'
const baz = Object.freeze(1) // Type is 1
const bar = Object.freeze([1, 2, 3]) // Type is [+1, +2, +3] (how to do read-only elements on tuple?)

goodmind avatar Jul 26 '19 16:07 goodmind

This would be really handy for objects as well. Some of our redux code at work defines constants objects like so:

const Constants = {
   Foo: ("Foo": "Foo"),
   Bar: ("Bar": "Bar"),
   ...
};

except the constants are much longer. It would be nice to be able to do:

const Constants = ({
   Foo: "Foo",
   Bar: "Bar",
   ...,
}: const);

kevinbarabash avatar Aug 04 '19 00:08 kevinbarabash

Thia is currently possible with Object.freeze, but only $Values supports it

goodmind avatar Aug 04 '19 08:08 goodmind

Does this mean $Values would return a tuple of type ["Foo", "Bar", ...]?

kevinbarabash avatar Aug 04 '19 19:08 kevinbarabash

@kevinbarabash, no, union

goodmind avatar Aug 04 '19 20:08 goodmind

something new here? this static type checker really has some potential but these missing typescript equivalent features prevent many of us from trying flow seriously...

Eliav2 avatar Oct 13 '21 21:10 Eliav2