# unknown_unit

> A function received a unit that isn't a unit ID, such as 'cups', or recipe input or quantity text has a unit Recipe Book doesn't recognize, such as 'cupz'.

Source: https://recipe-book.siraj.page/errors/unknown_unit/

`unknown_unit` is both an error code and an issue code:

- As an error code, it means a function received a unit that isn't a unit ID, such as the author text `'cups'`. See [Unit IDs in function calls](https://recipe-book.siraj.page/errors/unknown_unit.md#unit-ids-in-function-calls).
- As an issue code, it means recipe input or quantity text names a unit Recipe Book doesn't recognize, such as `'cupz'`. See [Units in recipe input and quantity text](https://recipe-book.siraj.page/errors/unknown_unit.md#units-in-recipe-input-and-quantity-text).

## Unit IDs in function calls

[`convert`](https://recipe-book.siraj.page/reference/core/units.md#convert), [`toSystem`](https://recipe-book.siraj.page/reference/core/units.md#tosystem), or [`getUnit`](https://recipe-book.siraj.page/reference/core/units.md#getunit) received a unit that isn't a [unit ID](https://recipe-book.siraj.page/reference/core/units.md#unitid). Usually it's text an author typed, such as `'cups'` or `'mL'`, passed where an ID such as `'cup'` or `'ml'` belongs.

```txt
RecipeBookError: "cups" is not a unit id. Use the id "cup"; findUnit("cups") converts author text to ids.
See https://recipe-book.siraj.page/errors/unknown_unit/
```

The ID the message names is the one [`findUnit`](https://recipe-book.siraj.page/reference/core/units.md#findunit) returns for the text, so for `'ounces'` it names `oz`, an ounce of mass, even if the author meant fluid ounces, `fl-oz`.

TypeScript rejects strings that aren't unit IDs, so this error comes from JavaScript, from a cast, or from data.

| Received                                                                                                                            | Message                                                                                                                |
| ----------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
| A typo near an alias, such as `'cupz'`                                                                                              | `Unknown unit "cupz". Did you mean "cup"?`                                                                             |
| A measurement system                                                                                                                | `"metric" is a measurement system, not a unit. To convert a quantity into a system, use toSystem(quantity, "metric").` |
| Another string, such as `'knob'`, `'packet'`, or `'cuppz'`                                                                          | `Unknown unit "knob". Use a unit id such as "g", "ml", or "cup".`                                                      |
| A value that isn't a string, such as `undefined` passed to `getUnit` or as `convert`'s target, `null`, `42`, an object, or an array | `Expected a unit id such as "g", "ml", or "cup", received undefined.`                                                  |

To compare a typo with an alias, `getUnit` ignores case, whitespace at either end, a period that ends a word, and punctuation at the end, and counts any other character, such as a hyphen or a digit, with any run of whitespace between words counting as one space. A typo is near an alias when what remains has at least three characters and differs from the alias by at most one character added, dropped, or changed, or two once it has six characters, with a swap of two neighboring characters counting as half of one. Shorter text, such as `'kg-'`, is near only an alias it matches, other than `T`, `t`, and `c`. A quantity whose `unit` is `undefined` has no unit, so `convert` throws [`incompatible_units`](https://recipe-book.siraj.page/errors/incompatible_units.md) for it instead, and `toSystem` returns it unchanged. Both throw [`invalid_argument`](https://recipe-book.siraj.page/errors/invalid_argument.md) first for an amount of 0, `NaN`, -1, or `Infinity`.

The unit IDs are `mg`, `g`, `kg`, `oz`, `lb`, `ml`, `cl`, `dl`, `l`, `tsp`, `tbsp`, `tbsp-au`, `fl-oz`, `cup`, `cup-metric`, `pint`, `quart`, `gallon`, `pinch`, `dash`, `clove`, `slice`, `piece`, `can`, `package`, `stick`, `sprig`, `bunch`, `head`, `bag`, `handful`, `jar`, and `stalk`. The [unit registry](https://recipe-book.siraj.page/reference/core/units.md#units) lists the aliases [`findUnit`](https://recipe-book.siraj.page/reference/core/units.md#findunit) accepts for each.

The formatters [`formatQuantity`](https://recipe-book.siraj.page/reference/core/formatting.md#formatquantity), [`formatQuantityToParts`](https://recipe-book.siraj.page/reference/core/formatting.md#formatquantitytoparts), and [`formatIngredient`](https://recipe-book.siraj.page/reference/core/formatting.md#formatingredient), and [`toJsonLd`](https://recipe-book.siraj.page/reference/core/schema-org.md#tojsonld) for an ingredient's quantities, name the unit they received and point to [`findUnit`](https://recipe-book.siraj.page/reference/core/units.md#findunit) and [`parseQuantity`](https://recipe-book.siraj.page/reference/core/parsing.md#parsequantity) instead of suggesting an ID. A quantity from [`parseRecipe`](https://recipe-book.siraj.page/reference/core/parsing.md#parserecipe), `parseQuantity`, or [`parseIngredientLine`](https://recipe-book.siraj.page/reference/core/parsing.md#parseingredientline) has a unit ID or no unit, so they throw this only for a quantity you build yourself:

```txt
RecipeBookError: formatQuantity: unit must be a unit id such as "g", "ml", or "cup", received "cups". findUnit converts author text to ids; parseQuantity also suggests a fix for a misspelling.
See https://recipe-book.siraj.page/errors/unknown_unit/
```

In React, [`<Recipe.Ingredients>`](https://recipe-book.siraj.page/reference/react/ingredients.md#ingredients), [`<Recipe.IngredientList>`](https://recipe-book.siraj.page/reference/react/ingredients.md#ingredientlist), [`<Recipe.Ingredient>`](https://recipe-book.siraj.page/reference/react/ingredients.md#ingredient), and the function that [`useFormatIngredient()`](https://recipe-book.siraj.page/reference/react/hooks.md#useformatingredient) returns throw it too, with a message that names `formatIngredient`, unless an equivalent shows instead, as in [`resolveRecipe`](https://recipe-book.siraj.page/reference/core/resolving.md#resolverecipe): the first native to Root's system, else in `'metric'` the first weight. [`<Recipe.JsonLd>`](https://recipe-book.siraj.page/reference/react/json-ld.md#jsonld) throws it even then, and for an equivalent with such a unit on an ingredient that has a quantity, with a message that names `toJsonLd`.

### Convert author text to unit IDs with `findUnit`

Casting author text to a unit ID passes it through unchecked, so `convert` throws:

```ts {4}
import { convert, type UnitId } from '@recipe-book/core'

function toMilliliters(amount: number, text: string) {
  return convert({ amount, unit: text as UnitId }, 'ml')
}

toMilliliters(1.25, 'cups')
```

Look up the ID with `findUnit`, which returns `undefined` for text that names no unit, and check it with [`canConvert`](https://recipe-book.siraj.page/reference/core/units.md#canconvert):

```ts {4-5}
import { canConvert, convert, findUnit } from '@recipe-book/core'

function toMilliliters(amount: number, text: string) {
  const unit = findUnit(text)
  if (!canConvert(unit, 'ml')) return undefined
  return convert({ amount, unit }, 'ml')
}

toMilliliters(1.25, 'cups') // { amount: 295.735295625, unit: 'ml' }
toMilliliters(1, 'knob') // undefined
```

When `findUnit` returns `undefined`, show the author's text as written rather than converting it.

## Units in recipe input and quantity text

[`parseRecipe`](https://recipe-book.siraj.page/reference/core/parsing.md#parserecipe) and [`parseQuantity`](https://recipe-book.siraj.page/reference/core/parsing.md#parsequantity) report an [`unknown_unit`](https://recipe-book.siraj.page/errors.md#issue-unknown_unit) issue when a quantity's unit isn't an alias in the [unit registry](https://recipe-book.siraj.page/reference/core/units.md#units). The parse fails with an [`invalid_recipe`](https://recipe-book.siraj.page/errors/invalid_recipe.md) or [`invalid_quantity`](https://recipe-book.siraj.page/errors/invalid_quantity.md) error.

A unit decides how a quantity scales and converts, so if the parser doesn't recognize one, it doesn't guess. When the text is a likely misspelling of a known alias, the message suggests that alias, and the issue's `suggestion` holds it, such as `'cups'` for `'1 ½ cupz'`. Other words get no suggestion, even one a letter off an alias, such as `'1 pan'`, as [Misspelled units](https://recipe-book.siraj.page/errors/invalid_ingredient.md#misspelled-units) shows for ingredient lines. In recipe input checked with `satisfies` [`RecipeInput`](https://recipe-book.siraj.page/reference/core/types.md#recipeinput), TypeScript rejects an unknown unit in a quantity object or at the end of quantity text, such as `'1 ½ cupz'`. It accepts a word before a known unit, though, so `'2 heaping tbsp'` type-checks, and the parse reports `heaping tbsp` as an unknown unit.

[`parseIngredientLine`](https://recipe-book.siraj.page/reference/core/parsing.md#parseingredientline), and `parseRecipe` when it reads ingredient lines with it, doesn't fail when the word after a line's amount is a likely misspelled unit, as in `'2 cupz flour'`. It warns instead, as [Misspelled units](https://recipe-book.siraj.page/errors/invalid_ingredient.md#misspelled-units) shows.

### Fix the unit or move the word into the name

A misspelled unit and a word that isn't a unit fail the parse:

```ts {6-7}
import { parseRecipe } from '@recipe-book/core'

const result = parseRecipe({
  name: 'Buttermilk pancakes',
  ingredients: [
    { name: 'all-purpose flour', quantity: '1 ½ cupz' },
    { name: 'blueberries', quantity: '2 punnets' },
  ],
  steps: ['Whisk everything together.'],
})
```

result.error.message
```txt title="result.error.message"
"Buttermilk pancakes" has 2 problems:
  ✖ ingredients[0].quantity  Unknown unit "cupz". Did you mean "cups"?
  ✖ ingredients[1].quantity  Unknown unit "punnets". Use a known unit, or move the word into the name: { name: "punnets", quantity: 2 }.
See https://recipe-book.siraj.page/errors/invalid_recipe/
```

Use the suggested unit, and move the other word into the ingredient's name, with a [`plural`](https://recipe-book.siraj.page/reference/core/types.md#ingredientinput):

```ts {6,8-9}
import { parseRecipe } from '@recipe-book/core'

const result = parseRecipe({
  name: 'Buttermilk pancakes',
  ingredients: [
    { name: 'all-purpose flour', quantity: '1 ½ cups' },
    {
      name: 'punnet of blueberries',
      plural: 'punnets of blueberries',
      quantity: 2,
    },
  ],
  steps: ['Whisk everything together.'],
})

result.success // true
```
