Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Question mark in callback

Tags:

react-native

static setItem(key: string, value: string, callback?: ?(error: ?Error) => void)

This is the declaration of setitem in AsyncStorage. the third parameter is a callback. Could some one explain the use of question marks here. I am familiar with how to use promise but couldn't get a handle of question mark.

like image 414
JEROM JOY Avatar asked Jul 03 '15 04:07

JEROM JOY


People also ask

What does question mark mean in TS?

Question marks on TypeScript variable are used to mark that variable as an optional variable. If we put the question mark when declaring a variable that variable becomes optional.

What does putting a question mark after a parameter name DP?

Question mark means "optional". So it's a shorthand for "parameter: type | undefined = undefined"..

Are question marks allowed in URL?

In a URL, the query starts with a question mark - the question mark is used as a separator, and is not part of the query string. If you also include a question mark in the query string, this would be treated as a literal question mark (i.e. it has no significance beyond that of a regular character).

What is question mark after variable JavaScript?

The question mark after the variable is called Optional chaining (?.) in JavaScript. The optional chaining operator provides a way to simplify accessing values through connected objects when it's possible that a reference or function may be undefined or null.


1 Answers

AsyncStorage uses flow - Facebook's open-sourced static type checker. You will find @flow at the beginning of the file and it marks flow-enabled source. Flow does a lot of checking on the variable types (including automated type inference) but it also lets you specify the types for variables and parameters. In the example above 'key: string' for example indicates that key should be string type (it's not a valid javascript construct - you cannot specify type in javascript). React has built in transformers that transform it to pure javascript (so all the types are stripped) but before that flow checks if types are passed around properly and find things like passing null or undefined and using it later as object and many other checks. You can read the specs in http://flowtype.org/.

So answering your detailed questionmark question:

  • '?Error' indicates that error parameter is a "Maybe" type - i.e. it CAN be null and flow will not complain if null or undefined is passed here elsewhere in the code callback (http://flowtype.org/docs/nullable-types.html#type-annotating-null)
  • 'callback?' indicates an optional parameter - so it might be skipped http://flowtype.org/docs/functions.html#function-based-type-annotations
  • '?(error...)' is another "Maybe" type - it simply indicates that the callback function might take one parameter ('error') or no parameters at all.
like image 112
Jarek Potiuk Avatar answered Oct 23 '22 18:10

Jarek Potiuk