Issue
I'm kind of writing a specific content scraper for some domains. So for those domains supported I just have some functions declared, let's just say there is a
export function getContent(html: string): string {}
So, I have many files with this exact interface for example ...
export interface Domain {
supportsHttps: boolean;
getContent(html: string): string;
}
And then for simplicity's sake (to make a map of supported hostname and my domains file), I just
// domainsList.ts
import * as domainA from './domains/domainA';
export default {
"www.domainA.com": domainA,
}
Then I import my domain list
// index.ts
import * as url from 'url';
import domains from './domainsList';
const maybeDomain: Domain | undefined = domains[url.parse(someUrl).host];
if (maybeDomain) {
// here I get proper autocompletion ...
const content = maybeDomain.getContent(someHtml);
} else {
throw new Error('domain not supported');
}
But if I refactor the name of the function in the interface from getContent to getContents for example, I actually do not have any compilation error from inside all the domains files.
I want to ensure ./domains/domainA.ts exported structure conforms to my Domain interface. Do I have a way to do that ?
Solution
Since you are not actually defining the function have the type of Domain the compiler won't link the two of them together, thus no errors.
Also, the Domain interface suits a class much better than a function.
You can get all the checks by defining classes instead of functions. Like this:
class AwesomeDomain implements Domain {
public supportsHttps: boolean;
getConten(html: string): string {
return '';
}
}
You can find a full example here.
Answered By - toskv Answer Checked By - Pedro (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.