A country name (any casing), e.g. "germany", "United States"
The matching ISO alpha-2 code, or undefined if the name is unknown
findCountryByName("germany") // "DE"
findCountryByName("United States") // "US"
findCountryByName("Narnia") // undefined
export function findCountryByName(name: string): CountryCode | undefined {
const titleCased = name
.trim()
.toLowerCase()
.replace(/\b[a-z]/g, (c) => c.toUpperCase());
const result: unknown = findByName(titleCased);
if (typeof result !== 'object' || result === null || !('code' in result)) {
return undefined;
}
const code: unknown = result.code;
if (typeof code !== 'object' || code === null || !('iso2' in code)) {
return undefined;
}
const iso2: unknown = code.iso2;
return typeof iso2 === 'string' && isKnownCountryCode(iso2) ? iso2 : undefined;
}
Resolves a country's ISO 3166-1 alpha-2 code from its full English name. Wraps the untyped
country-list-jsfindByName(whose record nests the code as{ code: { iso2 } }), title-casing the input first since the library matches only Title Case. Returns undefined for unknown names (including short aliases like "USA" that the library doesn't index — callers handle those separately).