Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

countries-ts

esmat-nawahda3.6kISC2.1.0TypeScript support: included

A powerful TypeScript library with 60+ functions for country data - search, validate, format, compare, and more. Zero dependencies.

countries, country, country-data, country-codes, iso-3166, currencies, languages, regions, capitals, flags, phone-codes, validation, search, typescript, country-list, country-information, country-search, country-validation, i18n, internationalization, geography

readme

Country Information Finder 🌎

A powerful and lightweight TypeScript library providing comprehensive country data and intelligent search capabilities. Access detailed information about countries including currencies, languages, capitals, regions, and more through an extensive API.

Features 🌟

  • Rich Data Source: Complete country data including codes, capitals, currencies, languages, flags, and phone codes
  • Advanced Search: Fuzzy search with field-specific filtering and advanced query options
  • Batch Operations: Process multiple countries efficiently in single operations
  • Type Safety: Full TypeScript support with detailed interfaces
  • Zero Dependencies: Lightweight and self-contained
  • 60+ Functions: Extensive API covering every use case
  • Validation Utilities: Built-in validators for country codes, currencies, and phone numbers
  • Export Capabilities: Export data as CSV or JSON
  • Comparison Tools: Compare countries by region, currency, and language

Installation 📦

# npm
npm install countries-ts

# yarn
yarn add countries-ts

# pnpm
pnpm add countries-ts

Quick Start 🚀

import { 
  searchCountries, 
  getByCode, 
  formatCountryName,
  getCurrencyDetails 
} from 'countries-ts';

// Search for countries
const countries = searchCountries('united');
// Returns: United States, United Kingdom, United Arab Emirates

// Get detailed country information
const usa = getByCode('US');
console.log(usa.capital); // Washington, D.C.

// Format country names
console.log(formatCountryName('US')); // United States of America (US)

// Get currency information
const usdInfo = getCurrencyDetails('USD');
console.log(usdInfo.countries); // List of countries using USD

Core API Reference 📘

Basic Queries

getByCode(code: string): Country | undefined

Get country by ISO 3166-1 alpha-2 code.

const japan = getByCode('JP');

getByAlpha2(alpha2: string): Country | undefined

Get country by ISO 3166-1 alpha-2 code (case-insensitive).

const usa = getByAlpha2('US');
const uk = getByAlpha2('gb'); // Case-insensitive

getByAlpha3(alpha3: string): Country | undefined

Get country by ISO 3166-1 alpha-3 code (case-insensitive).

const germany = getByAlpha3('DEU');
const canada = getByAlpha3('can'); // Case-insensitive

getByCountry(name: string): Country | undefined

Get country by name.

const france = getByCountry('France');

getByCodeArea(region: string): Country[]

Get countries by region code.

const europeanCountries = getByCodeArea('EU');

getByCurrency(code: string): Country[]

Get countries using a specific currency.

const euroCountries = getByCurrency('EUR');

getByLanguage(code: string): Country[]

Get countries by language code.

const spanishSpeaking = getByLanguage('es');

getByCountryCode(phoneCode: string): Country | undefined

Get country by phone code.

const country = getByCountryCode('+44'); // United Kingdom

listCountries(): Country[]

Get all countries.

const allCountries = listCountries();

Search & Filtering

searchCountries(query: string, fields?: (keyof Country)[]): Country[]

Search countries with fuzzy matching.

// Search in all default fields
const results = searchCountries('par');

// Search only in capitals
const capitals = searchCountries('paris', ['capital']);

searchCountriesAdvanced(query: string, filters?: SearchFilters): Country[]

Advanced search with multiple filters.

const filtered = searchCountriesAdvanced('a', {
  regions: ['EU', 'AS'],
  currencies: ['EUR', 'USD'],
  minPopulation: 1000000,
  maxArea: 500000
});

Batch Operations

getByMultipleCodes(codes: string[]): Country[]

Get multiple countries at once.

const countries = getByMultipleCodes(['US', 'CA', 'MX']);

validateCountryCodes(codes: string[]): { valid: string[], invalid: string[] }

Validate multiple country codes.

const result = validateCountryCodes(['US', 'XX', 'CA']);
// { valid: ['US', 'CA'], invalid: ['XX'] }

Currency Functions

getCurrencies(): CurrencyInfo[]

Get all unique currencies.

const allCurrencies = getCurrencies();

getByCurrencySymbol(symbol: string): Country[]

Get countries by currency symbol.

const dollarCountries = getByCurrencySymbol('$');

getCurrencyDetails(code: string): CurrencyInfo | undefined

Get detailed currency information.

const euroInfo = getCurrencyDetails('EUR');
// { code: 'EUR', label: 'Euro', symbol: '€', countries: [...] }

Region Functions

getRegions(): string[]

Get all region codes.

const regions = getRegions(); // ['AF', 'AS', 'EU', 'NA', 'OC', 'SA']

getRegionName(code: string): string

Convert region code to name.

const name = getRegionName('EU'); // 'Europe'

getRegionStats(): { region: string, count: number }[]

Get country count per region.

const stats = getRegionStats();

Language Functions

getLanguages(): LanguageInfo[]

Get all unique languages.

const languages = getLanguages();

getLanguageDetails(code: string): LanguageInfo | undefined

Get detailed language information.

const englishInfo = getLanguageDetails('en');

Validation & Formatting

isValidCountryCode(code: string): boolean

Validate country code.

isValidCountryCode('US'); // true
isValidCountryCode('XX'); // false

isValidCurrencyCode(code: string): boolean

Validate currency code.

isValidCurrencyCode('USD'); // true

isValidPhoneCode(code: string): boolean

Validate phone code.

isValidPhoneCode('+1'); // true

formatCountryName(code: string, format?: 'full' | 'short'): string | undefined

Format country name.

formatCountryName('US'); // 'United States of America (US)'
formatCountryName('US', 'short'); // 'United States of America'

formatPhoneNumber(number: string, countryCode: string): string | undefined

Format phone number with country code.

formatPhoneNumber('2025551234', 'US'); // '+1 2025551234'

Comparison & Analysis

compareCountries(code1: string, code2: string): ComparisonResult | undefined

Compare two countries.

const comparison = compareCountries('US', 'CA');
// { sameRegion: true, sameCurrency: false, sameLanguage: true }

getNeighboringCountries(code: string): Country[]

Get countries in the same region.

const neighbors = getNeighboringCountries('FR'); // Other EU countries

Sorting & Selection

sortCountriesBy(field: keyof Country | 'currency.code' | 'language.code', order?: 'asc' | 'desc'): Country[]

Sort countries by any field.

const byName = sortCountriesBy('label');
const byCapital = sortCountriesBy('capital', 'desc');

getRandomCountry(): Country

Get a random country.

const random = getRandomCountry();

getRandomCountries(count: number): Country[]

Get multiple random countries.

const randoms = getRandomCountries(5);

Capital Cities

getCapitals(): { country: string, capital: string }[]

Get all capitals sorted alphabetically.

const capitals = getCapitals();

getCountryByCapital(capital: string): Country | undefined

Find country by capital city.

const country = getCountryByCapital('Tokyo'); // Japan

ISO & Standards

getByIsoCode(iso: string): Country | undefined

Get country by ISO numeric code.

const country = getByIsoCode('840'); // United States

getIsoCodeMapping(): { [key: string]: string }

Get mapping of country codes to ISO codes.

const mapping = getIsoCodeMapping();
// { 'US': '840', 'GB': '826', ... }

Flag Utilities

getFlagUrl(code: string, size?: '48x36' | '96x72' | '192x144'): string | undefined

Get flag image URL.

const flag = getFlagUrl('JP', '96x72');

Export Functions

exportCountriesToCSV(): string

Export all countries as CSV.

const csv = exportCountriesToCSV();

exportCountriesToJSON(pretty?: boolean): string

Export all countries as JSON.

const json = exportCountriesToJSON(true);

Data Structure 📊

Country Interface

interface Country {
  label: string;           // Country name
  code: string;            // ISO 3166-1 alpha-2 code
  capital: string;         // Capital city
  region: string;          // Region code (EU, AS, etc.)
  currency: {
    code: string;          // Currency code (USD, EUR, etc.)
    label: string;         // Currency name
    symbol: string | null; // Currency symbol
  };
  language: {
    code: string;          // Language code
    label: string;         // Language name
  };
  flag: string;            // Flag image URL
  countryCode: string;     // Phone country code
  isoCode: string;         // ISO 3166-1 numeric code
  demonym?: string;        // Nationality name
  timezone?: string[];     // Timezones (future)
  coordinates?: {          // Geographic coordinates (future)
    latitude: number;
    longitude: number;
  };
  area?: number;           // Area in km² (future)
  population?: number;     // Population (future)
  borderCountries?: string[]; // Bordering countries (future)
  nativeName?: string;     // Native name (future)
  subregion?: string;      // Subregion (future)
}

Examples 💡

Building a Country Selector

import { searchCountries, formatCountryName, getFlagUrl } from 'countries-ts';

function CountrySelector({ searchTerm }: { searchTerm: string }) {
  const countries = searchCountries(searchTerm);

  return countries.map(country => ({
    value: country.code,
    label: formatCountryName(country.code, 'short'),
    flag: getFlagUrl(country.code, '48x36')
  }));
}

Currency Converter Helper

import { getCurrencyDetails, getByCurrency } from 'countries-ts';

function getCurrencyInfo(currencyCode: string) {
  const details = getCurrencyDetails(currencyCode);
  const countries = getByCurrency(currencyCode);

  return {
    ...details,
    countriesCount: countries.length,
    mainCountry: countries[0]?.label
  };
}

Regional Statistics

import { getRegionStats, getRegionName } from 'countries-ts';

function getRegionalAnalysis() {
  const stats = getRegionStats();

  return stats.map(stat => ({
    name: getRegionName(stat.region),
    code: stat.region,
    countries: stat.count,
    percentage: (stat.count / 249 * 100).toFixed(1) + '%'
  }));
}

Phone Validation

import { isValidPhoneCode, formatPhoneNumber, getByCode } from 'countries-ts';

function validateAndFormatPhone(number: string, countryCode: string) {
  const country = getByCode(countryCode);

  if (!country || !isValidPhoneCode(country.countryCode)) {
    throw new Error('Invalid country');
  }

  return formatPhoneNumber(number, countryCode);
}

Data Export

import { exportCountriesToCSV, getByCodeArea } from 'countries-ts';

// Export specific region as CSV
function exportRegionData(regionCode: string) {
  const countries = getByCodeArea(regionCode);
  const csv = countries.map(country => 
    `"${country.label}","${country.code}","${country.capital}","${country.currency.code}"`
  ).join('\n');

  return csv;
}

// Export all data
const fullCsv = exportCountriesToCSV();

Region Codes 🗺️

  • AF - Africa
  • AS - Asia
  • EU - Europe
  • NA - North America
  • OC - Oceania
  • SA - South America
  • AN - Antarctica

Performance 🚄

The library is designed for optimal performance:

  • Zero dependencies keep bundle size minimal
  • All operations run in memory for fast access
  • Efficient search algorithms for quick results
  • Tree-shakeable exports - only import what you need

TypeScript Support 🔷

Full TypeScript support with:

  • Complete type definitions for all functions
  • Detailed interfaces for all data structures
  • Proper return type inference
  • IDE autocompletion support

Browser Support 🌐

Works in all modern browsers and Node.js environments:

  • Chrome, Firefox, Safari, Edge (latest versions)
  • Node.js 12+
  • React Native compatible

Contributing 🤝

We welcome contributions! Please see our Contributing Guidelines for details.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

License 📄

This project is licensed under the MIT License - see the LICENSE file for details.

Changelog 📝

v2.0.0 (Latest)

  • Added 50+ new functions
  • Advanced search capabilities
  • Batch operations support
  • Currency and language utilities
  • Region statistics and mapping
  • Validation and formatting helpers
  • Export functionality (CSV/JSON)
  • Comparison and analysis tools
  • Flag URL utilities
  • Random country selection
  • ISO code support
  • Performance improvements

v1.0.0

  • Initial release
  • Basic country queries
  • TypeScript support

Support 💬


Made with ❤️ by the community. Special thanks to all contributors!

changelog

Changelog

All notable changes to this project will be documented in this file.

The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.

[2.0.0] - 2024-01-XX

Added

  • Search & Filtering

    • searchCountries() - Fuzzy search across multiple fields
    • searchCountriesAdvanced() - Advanced search with filters
    • getByMultipleCodes() - Get multiple countries at once
    • getByCurrencySymbol() - Find countries by currency symbol
  • Region & Geography

    • getRegions() - List all regions
    • getRegionStats() - Statistics per region
    • getRegionName() - Convert region codes to names
    • getRegionsWithNames() - Regions with full names and counts
    • getNeighboringCountries() - Countries in same region
    • getCountriesByRegions() - Filter by multiple regions
  • Currency Features

    • getCurrencies() - All unique currencies
    • getCountriesUsingCurrency() - Count countries using a currency
    • getCurrencyDetails() - Detailed currency information
  • Language Features

    • getLanguages() - All unique languages with null check
    • getCountriesByLanguages() - Filter by multiple languages
    • getLanguageDetails() - Detailed language information
  • Validation Utilities

    • isValidCountryCode() - Validate country codes
    • isValidCurrencyCode() - Validate currency codes
    • isValidPhoneCode() - Validate phone codes
    • validateCountryCodes() - Batch validation
  • Formatting Helpers

    • formatCountryName() - Format with full/short options
    • formatPhoneNumber() - Format phone numbers with country code
  • Comparison & Analysis

    • compareCountries() - Compare region, currency, language
    • sortCountriesBy() - Sort by any field
    • getCountryStatistics() - Overall statistics
    • getDistanceBetweenCountries() - Calculate distance (future use)
    • getPopulationDensity() - Calculate density (future use)
  • Random Selection

    • getRandomCountry() - Get one random country
    • getRandomCountries() - Get multiple random countries
  • Capital City Features

    • getCapitals() - All capitals sorted
    • getCountryByCapital() - Find country by capital
  • ISO Code Support

    • getByIsoCode() - Find by ISO numeric code
    • getIsoCodeMapping() - Map country codes to ISO codes
  • Export Capabilities

    • exportCountriesToCSV() - Export as CSV
    • exportCountriesToJSON() - Export as JSON
  • Batch Operations

    • getCountriesBatch() - Get multiple countries with validation
  • Flag Utilities

    • getFlagUrl() - Get flag URLs in different sizes
  • Future-Ready Features

    • getMostPopulousCountries() - Population rankings
    • getLeastPopulousCountries() - Population rankings
    • getLargestCountries() - Area rankings
    • getSmallestCountries() - Area rankings
    • getCountriesInTimezone() - Timezone filtering
    • getCountriesByCoordinates() - Geographic search
    • getBorderingCountries() - Border countries
    • areBorderingCountries() - Check if bordering
    • getByDemonym() - Find by nationality
    • getDemonyms() - List all demonyms
    • getByNativeName() - Find by native name
    • getNativeNames() - List native names
    • getSubregions() - List subregions
    • getCountriesBySubregion() - Filter by subregion

Enhanced

  • Country interface now includes optional fields for future expansion:
    • timezone - Array of timezones
    • coordinates - Latitude and longitude
    • area - Area in km²
    • population - Population count
    • borderCountries - Array of border country codes
    • nativeName - Native language name
    • subregion - Subregion classification
    • demonym - Nationality name

Changed

  • Improved TypeScript types with new interfaces:
    • RegionInfo - Region with name and country count
    • CurrencyInfo - Currency with countries using it
    • LanguageInfo - Language with countries speaking it
    • CountryStats - Overall statistics interface
    • SearchFilters - Advanced search filter options

Fixed

  • Language sorting now handles null codes properly
  • All functions maintain backward compatibility

[1.0.3] - Previous Release

Fixed

  • Minor bug fixes and improvements

[1.0.2] - Previous Release

Fixed

  • Documentation updates

[1.0.1] - Previous Release

Fixed

  • Initial bug fixes

[1.0.0] - Initial Release

Added

  • Basic country query functions:
    • getByCodeArea() - Get by region
    • getByCode() - Get by country code
    • getByCountry() - Get by country name
    • getByCurrency() - Get by currency code
    • getByLanguage() - Get by language code
    • getByCountryCode() - Get by phone code
    • listCountries() - List all countries
  • TypeScript support
  • Comprehensive country data