Why doesn't an object type have a specific subtype of an object type with the prop option in Flow?

In the stream, I can declare an object type with an optional option, so an object with this support satisfies it.

function getName(thing: {name?: string}): string {
  return thing.name || 'unknown';
}
getName({name: 'bob'}); // works

But if I declare an object type for a parameter before passing it, Flow will log an error.

const thing: {name: string} = {name: 'bob'};
getName(thing); // error

So, why does a type with a specific support not match a type with the same name as the option? How can I fix these annotations?

+4
source share
1 answer

When you declare a type

function getName(thing: {name?: string}): string {
  return thing.name || 'unknown';
}

this means that the type will be used for your function

function getName(thing: {name?: string}): string {
  thing.name = undefined;
  return "anything";
}

because you said it was nameallowed to be undefined.

Given that

const thing: {name: string} = {name: 'bob'};
getName(thing); // error

will break type safety, the value will no longer be a string.

. , , , name .

function getName(thing: { +name?: string }): string {
  return thing.name || 'unknown';
}

Flow , name . , {name: string}, .

+5

Source: https://habr.com/ru/post/1688418/


All Articles