Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Google libphonenumber in Typescript?

I want to use Google libphonenumber in my angular project using Typescript. I have searched a lot on the internet and found a lot of stuff but could not find anything that could serve my purpose.

Most of the content available shows the code in JavaScript. If I use the same code in typescript, it shows a lot of errors like cannot find name require or module not found. Please tell me how/where/what to write the code.

Also, plz tell me which package to install as there are many - libphonenumber, google-libphonenumber, angular-libphonenumber

like image 785
Ashish Singh Avatar asked Mar 15 '18 07:03

Ashish Singh


2 Answers

When dealing with CommonJS libraries, in TypeScript just like this google-libphonenumber, I'd like to suggest 2 ways about it (Tested by me and works well).

Initially, I'd like to suggest to install from NPM just like this: npm install --save google-libphonenumber.

Then, here we go both ways of using it:

1st Method

Just import it directly

import libphonenumber from 'google-libphonenumber';
class Something {
    constructor() {//Just example, you can chose any method
        const phoneUtil = libphonenumber.PhoneNumberUtil.getInstance();
        console.log( phoneUtil.getSupportedRegions() );//It should works and give you some output
    }
}

2nd Method

You still can make the power of Typescript typing or just use the existing one by: npm install --save-dev @types/google-libphonenumber.

Since you said that you using Angular, so you can declare that typing just installed at src/tsconfig.app.json ( I am using Angular Version 7 ). Here is an example I have made:

{
  ...
  "compilerOptions": {
    ...
    "types": [
      "google-libphonenumber"
    ]
  },
  ...
}

Then you can just import it like usual, in Typescript "typings" way like follow:

import { PhoneNumberUtil } from 'google-libphonenumber';

class Something {
    constructor() {//Just example, you can chose any method
        const phoneUtil: PhoneNumberUtil = PhoneNumberUtil.getInstance();
        console.log( phoneUtil.getSupportedRegions() );//It should works and give you some output
    }
}
like image 190
Bayu Avatar answered Oct 14 '22 23:10

Bayu


you may either go with libphonenumber or google-libphonenumber as both of this library having a good number of installs also google-libphonenumber seems to be more powerful

like image 35
Santosh Singh Avatar answered Oct 14 '22 22:10

Santosh Singh