Design patterns with Typescript
npm install -g parcel-bundler
Tool to help us run Typescript in the browser
npmjs.com=>‘faker’ package
npm install faker
npm install @types/faker
Typescript Code => Type definition file => JS Library
- Definitely typed Naming Scheme =>
@type/{library name}
=>eg:@types/faker
npm install @types/googlemaps
- Demo APP
index.html
<html>
<body>
<div id="map" style="height: 100%"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBNLrJhOMz6idD05pzfn5lhA-TAw-mAZCU"></script>
<script src="./src/index.ts"></script>
<!-- index.ts---Map.ts
|-User.ts
|-Company.ts -->
</body>
</html>
index.ts
import { User } from './User';
import { CustomMap } from './CustomMap';
import { Company } from './company';
const user = new User();
const company = new Company();
// console.log(user);
// console.log(company);
//CustomMap
// --new
// |-addMarker
const customMap = new CustomMap('map');
customMap.addMarker(user);
customMap.addMarker(company);
CustomMap.ts
import { User } from './User';
import { Company } from './Company';
//Instructions to every other class
//on how they can be argument to add marker
export interface Mappable {
location: {
lat: number;
lng: number;
};
markerContent(): string;
color: string;
}
export class CustomMap {
private googleMap: google.maps.Map;
constructor(divId: string) {
this.googleMap = new google.maps.Map(document.getElementById(divId), {
zoom: 1,
center: {
lat: 0,
lng: 0,
},
});
}
addMarker(mapable: Mappable): void {
const marker = new google.maps.Marker({
map: this.googleMap,
position: {
lat: mapable.location.lat,
lng: mapable.location.lng,
},
});
const infoWindow = new google.maps.InfoWindow({
content: mapable.markerContent(),
});
marker.addListener('click', () => {
infoWindow.open(this.googleMap, marker);
});
}
// addCompanyMarker(company: Company): void {
// new google.maps.Marker({
// map: this.googleMap,
// position: {
// lat: company.location.lat,
// lng: company.location.lng,
// },
// });
// }
}
Company.ts
import faker from 'faker';
import { Mappable } from './CustomMap';
export class Company implements Mappable {
companyName: string;
catchPhrase: string;
location: {
lat: number;
lng: number;
};
color: string = 'yellow';
constructor() {
this.companyName = faker.company.companyName();
this.catchPhrase = faker.company.catchPhrase();
this.location = {
lat: parseFloat(faker.address.latitude()),
lng: parseFloat(faker.address.longitude()),
};
}
markerContent(): string {
return `User Name:${this.companyName}`;
}
}
User.ts
import faker from 'faker';
import { Mappable } from './CustomMap';
//typescript 不用export default
export const red = 'red';
export class User implements Mappable {
name: string;
location: {
lat: number;
lng: number;
};
color: string = 'red';
constructor() {
this.name = faker.name.firstName();
this.location = {
lat: parseFloat(faker.address.latitude()),
lng: parseFloat(faker.address.longitude()),
};
}
markerContent(): string {
return `User Name:${this.name}`;
}
}