PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, August 24, 2022

[FIXED] How to make sure a typescript module conforms to an interface

 August 24, 2022     interface, javascript, module, typescript     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing