facebook / facebook/flow

%checks type refinement function for opaque alias types

Aperta
#5,563 1 commento 1 reazione 0 assegnatari Vedi su GitHub
Typing: opaque types Typing: refinements
Lingua principale
Rust
Stelle
22.3k
Fork
1.9k
Metriche di merge delle PR
Nessuna PR unita negli ultimi 30g

Descrizione

I'm using opaque alias types described here: https://flow.org/en/docs/types/opaque-types/

I'm also using the undocumented `checks%` hack to define type refinement functions, for example

```js
declare function isHash(x: mixed): boolean %checks(typeof x === "string");
```

and the actual function is defined as

```js
function isHash (thing: mixed): boolean {
return typeof thing === 'string' && StorageBaseCommon.CRYPTO_HASH_RE.test(thing);
}
```

_(I have a reason for using a separate `declare` statement to have the `%checks` on instead of putting it right on the actual function, but that's not important now.)_

My problem is that I don't seem to have a way to write a type refinement function for an opaque alias type?

For example, I use SHA-256 hashes in my code, which are strings, but very special strings (obviously). So I'm using an alias

```js
export opaque type SHA256Hash: string = string;
```






It's very unfortunate that I can't just tell Flow that a function checks a given type, that I can only use `typeof` and `instanceof`. That only works for "fake OOP" class-based programming where `instanceof` works. It doesn't work for a functional style when I have just different kinds of plain objects and no inheritance and nothing is constructed using `new`. And plain types cannot be aliased if only `typeof` is allowed for refinement.

Guida per i contributori

Apri la guida per i contributori

Valutazione

Questa issue non è ancora stata valutata.

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.