getCountry()function
Parse a country string, or detect a browser country from navigator.language.
getCountry(value: unknown = "detect"): Country | undefined
Country codes, names, and address formatting. Provides the COUNTRIES lookup (ISO 3166-1 alpha-2), typed Country and AddressData types, and helpers for parsing and displaying country information.
Things to know:
getCountry() with "detect" reads navigator.language in the browser to guess the user's country — it returns undefined in non-browser environments or when the locale cannot be mapped to a country code.formatCountry() is tolerant of unknown codes — it returns the input string unchanged rather than throwing.import { getCountry, requireCountry, formatCountry } from "shelving/util";
getCountry("gb"); // "GB"
getCountry("XX"); // undefined (unknown code)
getCountry("detect"); // "US" (inferred from navigator.language in browser)
requireCountry("gb"); // "GB"
requireCountry("XX"); // throws RequiredError
formatCountry("GB"); // "United Kingdom"
formatCountry("XX"); // "XX" (passthrough for unknown codes)import { formatAddress } from "shelving/util";
const addr = {
address1: "10 Downing Street",
address2: "",
city: "London",
state: "England",
postcode: "SW1A 2AA",
country: "GB",
};
formatAddress(addr);
// "10 Downing Street\nLondon\nEngland\nSW1A 2AA\nUnited Kingdom"import { COUNTRIES } from "shelving/util";
const name = COUNTRIES["FR"]; // "France"
const codes = Object.keys(COUNTRIES); // ["AF", "AX", ...]Parse a country string, or detect a browser country from navigator.language.
getCountry(value: unknown = "detect"): Country | undefined
Parse a country string, or detect a browser country from navigator.language, or throw RequiredError.
requireCountry(value?: unknown, caller: AnyCaller = requireCountry): Country
Format a country code into its full country name.
formatCountry(country: string): string
Format address data into a single multiline string.
formatAddress({ address1, address2, city, state, postcode, country }: AddressData): stringTwo-letter ISO 3166-1 alpha-2 country code string (a key of COUNTRIES).
keyof typeof COUNTRIES
A value that can possibly be resolved to a Country — either a country code or the literal "detect".
Country | "detect"
Valid shape for physical address data.
{
readonly address1: string;
readonly address2: string;
readonly city: string;
readonly state: string;
readonly postcode: string;
readonly country: Country;
}List of countries by two-letter ISO 3166-1 alpha-2 code.