Skip to content

Instantly share code, notes, and snippets.

@dotherightthing
Last active September 6, 2019 04:47
Show Gist options
  • Save dotherightthing/13fbc18780485a8e1877aa82adda51e4 to your computer and use it in GitHub Desktop.
Save dotherightthing/13fbc18780485a8e1877aa82adda51e4 to your computer and use it in GitHub Desktop.
[Type declarations] #php #javascript #naturaldocs #phpdocumentor #typescript #typehinting

Type declarations

AKA Type hinting.

Background

I used to use phpDocumentor. It had this nice feature where you could document:

  1. the type of input that was expected
  2. the type of output that was expected

This was a handy reference when using functions.

I lost this functionality when I switched to Natural Docs - or so I thought.

PHP

Function arguments

phpDocumentor

/**
 * my_function
 *
 * @param array $an_array An array
 * @param bool $a_boolean A boolean
 * @param int $a_number A number
 * @param object $an_object An object
 * @param string $a_string A string
 */
public function my_function(
  $an_array,
  $a_boolean,
  $a_number,
  $an_object,
  $a_string
) {
    ...
}

Natural Docs + PHP5+

/**
 * Function: my_function
 *
 * Parameters:
 *   $an_array - An array (PHP 5.1)
 *   $a_boolean - A boolean (PHP 7.0)
 *   $a_number - A number (PHP 7.0)
 *   $an_object - An object (PHP 7.2)
 *   $a_string - A string (PHP 7.0)
 */
public function my_function(
  array $an_array,
  bool $a_boolean,
  int $a_number,
  object $an_object,
  string $a_string
) {
    ...
}

See also other Valid types.

Natural Docs picks up on this and displays the input type just the same as if I had specified it inside curly brackets.

More importantly, the value can be checked by the linting/testing engine.

Function returns

phpDocumentor

/**
 * my_function
 *
 * @return string $content
 */
public function my_function() {
    $content = 'hello world';
    return $content;
}

Natural Docs + PHP7

/**
 * Function: my_function
 *
 * Returns:
 *   $content - Content
 */
public function my_function() : string {
    $content = 'hello world';
    return $content;
}

If you're not sure whether your string will be returned or not, you can do prefix the type with a question mark:

/**
 * Function: my_function
 *
 * Returns:
 *   $content - Content
 */
public function my_function() : ?string {
    if ( $something ) { 
      $content = 'hello world';
      return $content;
    } else {
      return null;
    }
}

Unfortunately the current version of Natural Docs doesn't pick up on this.

JavaScript

This led me to realise what TypeScript was all about.

TODO

Links

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment