peerigon/parse-domain

typescript issue

its-dibo opened this issue · 2 comments

for this example:

import { parseDomain } from "parse-domain";
let parts = parseDomain("www.google.com");

console.log(parts.subDomains)

//error TS2339: Property 'subDomains' does not exist on type 'ParseResult'.
  Property 'subDomains' does not exist on type 'ParseResultInvalid'

trying to add type for parts.

let parts: ParseResultListedDomains=parseDomain("www.google.com");

but parse-domain dosen't export ParseResultListedDomains type.

solved by using ParseResultListed instead of ParseResultListedDomains

let parts: ParseResultListed = <ParseResultListed>parseDomain("www.google.com");
jhnns commented

Please read the README :)

If you called parseDomain() with an invalid domain, there won't be a subDomains property. You need to check for the returned type:

import {parseDomain, ParseResultType} from "parse-domain";

const parseResult = parseDomain("www.google.com");

switch (parseResult.type) {
	case ParseResultType.Listed: {
		const {hostname, topLevelDomains} = parseResult;

		console.log(`${hostname} belongs to ${topLevelDomains.join(".")}`);
		break;
	}
	case ParseResultType.Reserved:
	case ParseResultType.NotListed: {
		const {hostname} = parseResult;

		console.log(`${hostname} is a reserved or unknown domain`);
		break;
	}
	default:
		throw new Error(`${hostname} is an ip address or invalid domain`);
}

TypeScript is trying to warn you and you're disabling that warning :)