Athyuttam Eleti
Athyuttam Eleti

Reputation: 609

How to convince Flow that a value meets the generic type?

I have the following Flow-typed code:

/* @flow */

type Foo = 1;

const DefaultFoo: Foo = 1;

function getDefault<T: Foo>(): T {
  return DefaultFoo;
}

When I try to run it, here's the error I get:

8:   return DefaultFoo;
            ^ number literal `1`. This type is incompatible with the expected return type of
7: function getDefault<T: Foo>(): T {
                                  ^ T

Here's a flow.org/try link: https://flow.org/try/#0PQKgBAAgZgNg9gdzCYAoVAXAngBwKZgBiccYAvGAIwDc6AxnAHYDOGYAInlAIYCuMGYnABcREuSq1UUXozoYAlkzABzPBk49+GADwAVUUIB8ACgCUovWADeqMGABO63g8YcufAUNoBfIA

Could someone explain what's wrong with the code, and how I can convince Flow that DefaultFoo is indeed of type T?

Upvotes: 1

Views: 49

Answers (1)

Aleksey L.
Aleksey L.

Reputation: 37918

The assumption that DefaultFoo is of type T is wrong.
Have a look at this example (Bar is our T in this case):

type Foo = {};

interface Bar extends Foo {
  bar(): void;
}

const DefaultFoo: Foo = {};

Bar extends Foo, so Bar is a Foo but not the other way around.
DefaultFoo is not a Bar

Upvotes: 1

Related Questions