0

I have a Value type like this:

export type Value = {
   __typename?: 'Value',
  key?: Maybe<Scalars['String']>,
  label?: Maybe<Scalars['String']>,
  value?: Maybe<Scalars['String']>,
};

And a query result type (generated apollo hooks) like this:

Maybe<Maybe<{
    __typename?: "Value" | undefined;
} & Pick<Value, "key" | "label" | "value">>[]>

I'm trying to pass this query result to a function:

const getValues = (contacts: Value[]) => {
  const values = contacts.map(e => e["value"]);
  return values;
};

For some reason, TypeScript says that those types are incompatible. My function call:

getValues( dataFilters!.caseListFilters!.contacts ) 

TypeScript error:

Argument of type 'Maybe<Maybe<{ __typename?: "Value" | undefined; } & Pick<Value, "key" | "label" | "value">>[]>' is not assignable to parameter of type 'Value[]'.
  Type 'null' is not assignable to type 'Value[]'.ts(2345)

Can someone help me to understand what is wrong with these types? I know that as Value[] solves the problem but I have no idea why.

getValues( dataFilters!.caseListFilters!.contacts as Value[] //no error )
platinum_ar
  • 127
  • 3
  • 8

1 Answers1

0

You have Maybe types, which are nullables at a higher order. So although you assert that they are not undefined using !, you are asserting that they are in fact Maybe the thing. A thing of Maybe type, when it is there, is still only maybe the value.

For a maybe you have to unwrap the value safely to get a guaranteed value.

Where is the Maybe type from? Sanctuary.js? fp-ts? Go to Definition and understand what Maybe type you are using, then read the docs. You need to get the value out of it.

Josh Wulf
  • 4,727
  • 2
  • 20
  • 34
  • Thank you, but I understand only the first part of your answer. What it means to "unwrap the value safely"? I came across [true-myth](https://true-myth.js.org/modules/_maybe_.html) where they talk about unwrapping Just and Nothing, but all I've found regarding my Maybe implementation is this: `export type Maybe = T | null;` – platinum_ar May 11 '20 at 11:24