Skip to contents

The @typed tag introduces a syntax for defining parameter types as a roxygen2 tag.

Usage

#' @typed <var>: <type>
#'   <description>

Details

Be aware that there are a few syntactic requirements:

  • : delimiter between the variable name and type.

  • \n after the type to separate it from the description.

Default type Parsing Syntax

The type portion of the @typed tag syntax will handle a bit of syntax as special cases.

  • [type]: Types wrapped in brackets, for example [roxygen2::roxy_tags()] will be left as-is, without wrapping the string in backticks to display as inline code and preserve the native roxygen2 reference link.

    #' @typed arg: [package::function()]
    #'   long form description.

  • `type`: Types wrapped in backticks will be kept as-is. Additional backticks will not be inserted.

    #' @typed arg: `class`
    #'   long form description.

  • "type" or 'type': Types wrapped in quotes (either single or double), will be provided as literal values, removing the surrounding quotation marks.

    #' @typed arg: "`class_a` or `class_b`"
    #'   depending on the class of the object provided, either an `"A"`
    #'   or a `"B"`.

Custom type Parsing Function

The above defaults are meant to cover most use cases and should be sufficient for all but the most elaborate development practices. If you need to go beyond these default behaviors, you can also provide a parsing function, accepting the parsed roxygen tag as well as the raw contents.

The function accepts the roxygen2::roxy_tag() produced when parsing the tag, whose $val contains fields name, type and description. For convenience, the $val contents is unpacked as arguments, though the structure of this tag is liable to change.

To implement a typescript-style class union syntax,

#' @typed arg: class_a | class_b | class_c
#'   depending on the class of the object provided, either an `"A"`
#'   or a `"B"`.

to produce the parameter definition

(`class_a`, `class_c` or `class_b`) depending on the class of the object
provided, either an `"A"`, `"B"` or a `"C"`.

we might define the following in DESCRIPTION (or in man/roxytypes/meta.R).

Config/roxytypes: list(
  format = function(tag, ..., name, type, description) {
    types <- paste0("`", trimws(strsplit(type, "|", fixed = TRUE)[[1]]), "`")
    types <- glue::glue_collapse(types, sep = ", ", last = " or ")
    paste0("(", types, ") ", description)
  }
)