[Typescript] Syntax cleanup
a look at interface and type declarations
Creating and using interfaces
interfaceinterface IUser {
name: string;
id: number;
}
class UserAccount {
name: string;
id: number;
constructor(name: string, id: number) {
this.name = name;
this.id = id;
}
}
const user: IUser = new UserAccount("Murphy", 1);
- in class UserAccount, the name and id fields exist, so they satisfy the given interface.
- the types of the fields are also validated.
when you specify an argument or return type in a function, you can...
arguments, return type
const user: IUser = new UserAccount("Murphy", 1);
/**]
* function to pick out people with names longer than 20 characters
*/]
const filterWithLongName = (user:IUser) => user.name.length > 20;
1.1. Define the interface
Typescript interface
interface ILoc {
lat: number,
lng: number
};
class Hotel {
name:string;
id: number;
lat:number;
lng:number
constructor(id:number, name:string, lat:number, lng:number) {
this.name = name
this.id = id
this.lat = lat;
this.lng = lng;
}
}
class Busstop {
stationId:string;
lat:number;
lng:number;
constructor(stationId:string, lat:number, lng:number) {
this.stationId = stationId;
this.lat = lat;
this.lng = lng;
}
}
const members:ILoc[] = [];
members.push(new Hotel(98344,"awesome hotel", 12.3344, -135.1124));
members.push(new Hotel(47590,"so so beautiful hotel", 126.02993, 23.9013));
members.push(new Busstop("of283jf-sakkk2-gkk2k2", 123.3316, 11.93883));
- different classes can be held in one array as long as the names and types of the fields specified in the interface exist.
- it is okay to have separate fields except lat, lng.
you can also add an object literal for the above interface.
Typescript interfacembers.push(new Hotel(47590,"so so beautiful hotel", 126.02993, 23.9013));
members.push(new Busstop("of283jf-sakkk2-gkk2k2", 123.3316, 11.93883));
members.push({lat: 123.3316, lng: 11.93883});
- allow lat, lng fields to be object literals if defined