Juan Carlos Serrano
Juan Carlos Serrano

Reputation: 103

Why Flow can not infer type with default value of method parameter

When you code this method:

   // @flow

   function greeting (name: string = 8): string {
    return `Hello ${name}!!`
   }

Flow check that default value is wrong, ok for me, but with this code:

   // @flow

   function greeting (name = 'world'): string {
    return `Hello ${name}!!`
   }

   greeting(8)

there is not an error with use a number argument, as i expect like that

   function greeting (name: string = 'world'): string {
    return `Hello ${name}!!`
   }

Why can not infer the type with the default value?

Thank in advance.

Upvotes: 0

Views: 167

Answers (1)

silicakes
silicakes

Reputation: 6902

That's because in your example, the function returns a string, but there's no type stated for the name parameter.

Since you're interpolating name into a string, using backticks (``), its type will implicitly convert to string even if it's a number. So as long as you return a string - your notation is ok.

If you'd like flow to error, you can do the following:

function greeting (name: string = "name"): string {
    return `Hello ${name}!!`
   }

Then when you'll call it like so:

greeting(8);

you'll get the following error:

greeting(8)
            ^ Cannot call `greeting` with `8` bound to `name` because number [1] is incompatible with string [2].
References:
6: greeting(8)
            ^ [1]
2: function greeting (name: string = "name"): string {

The whole thing is around inference. Imagine the following case:

function(name: string | number = "name") {.. In this notation name can be either string or a number.

Flow has no way of knowing your intention with a default value, so it infers everything as any

Upvotes: 1

Related Questions